java多线程——我这样做对吗?
我想看一下单线程和多线程的区别,于是写下啦下面的代码:
public class ThreadFight implements Runnable {
public void run() {
long a = System.currentTimeMillis();
int i = 0;
BufferedWriter buff = null;
try {
buff = new BufferedWriter(new FileWriter("d:\\log.txt"));
} catch (IOException e1) {
e1.printStackTrace();
}
while (System.currentTimeMillis() - a <= 2000) {
try {
String str = Thread.currentThread().toString() + i++;
buff.write(str);
buff.write("\r\n");
buff.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
buff.close();
System.err.println("OVER, and i is " + i);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main1(String[] args) {
ThreadFight fight = new ThreadFight();
Thread thread = new Thread(fight);
thread.start();
}
public static void main2(String[] args) {
ThreadFight fight = new ThreadFight();
ThreadFight fight2 = new ThreadFight();
Thread thread2 = new Thread(fight2);
Thread thread = new Thread(fight);
thread.start();
thread2.start();
}
public static void main(String[] args) {
main1(args);
//main2(args);
}
}
但是奇怪的发现,分别执行main1和main2,结果差不多。我做错了吗?
[解决办法]
你用一个输出线程的话只能输出一个thread0,你用两个输出线程的话会交替输出thread0和thread1啊。你说结果差不多的原因在于你用两个线程创建filewriter一个会覆盖上一个,所以每次只能显示出一个,所以结果和单输出线程是差不多的。