日期:2014-05-20  浏览次数:20695 次

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一个会覆盖上一个,所以每次只能显示出一个,所以结果和单输出线程是差不多的。
探讨

引用:
你两个都是多线程,main函数也是一个线程啊
但是对于输出只有一个线程啊。

------解决方案--------------------
对于一个处理器来说,同步并不是真正意义上的同步,只是cpu合理分配资源,让线程交替使用cpu,呈现出同步的状态。
探讨

哦,这样啊。其实我想知道多线程在单核和双核CPU上的区别,还有多线程是否是同步执行的。我这样做可以吗?引用:
你用一个输出线程的话只能输出一个thread0,你用两个输出线程的话会交替输出thread0和thread1啊。你说结果差不多的原因在于你用两个线程创建filewriter一个会覆盖上一个,所以每次只能显示出一个,所以结果和单输出线程是差不多的。

引用 2 楼 ……