Check out this link: bipolar
NOTE: There is a bug relating to concurrency and threads in this code! Can you find it?
import java.io.*;
import java.util.*;
public class ThreadFileOut {
private static int tcount=0;
private static String prefix;
private static Hashtable<Thread,PrintStream> table;
public ThreadFileOut(String prefix) {
this.prefix = prefix;
this.table = new Hashtable<Thread,PrintStream>();
}
public static void println(String s) {print(s+"\n");}
public static void print(String s) {
try {
Thread current = Thread.currentThread();
PrintStream ps = table.get(current);
if (ps==null) {
tcount++;
ps = new PrintStream(new FileOutputStream(prefix+"."+tcount+".out"));
table.put(current,ps);
}
ps.print(s);
} catch (IOException ioe) {System.err.println("IOException in ThreadFileOut: "); Thread.dumpStack(); System.err.println(ioe);}
}
}
public class TFOTest extends Thread {
private static int n;
private int id;
public TFOTest(int i) {id=i;}
public void run() {
for (int j=0; j<n*20; j++) {
ThreadFileOut.print(""+id);
if (j%50==0) ThreadFileOut.print("\n");
}
}
public static void main(String[] a) {
n = Integer.parseInt(a[0]);
ThreadFileOut tfo = new ThreadFileOut("dma");
for (int i=0; i<n; i++)
new TFOTest(i+1).start();
}
}