java 线程问题
public class Thread4 extends Thread{/**
* @param args
*/
private Threadb tb ;
public Thread4(Threadb tb){
this.tb = tb;
}
public void run(){
synchronized(tb){
try {
System.out.println(Thread.currentThread() + " wait ......");
tb.wait(); ///如果没有ta.wait()则函数直接顺序执行下去,输出的值不是预期的。
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
System.out.println(Thread.currentThread() + "------------>" + tb.getTotal());
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Threadb tb = new Threadb();
new Thread4(tb).start();
new Thread4(tb).start();
new Thread4(tb).start();
tb.start();
}
}
class Threadb extends Thread{
private int total;
public int getTotal(){
return total;
}
public void run(){
total = 0;
synchronized(this){
for(int i = 0; i < 101; i ++){
total += i;
try {
Thread.sleep(50);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
this.notifyAll();
}
}
}
//结果不是唯一,并且有时候结果不正常。
结果如下:
1.没有输出第三个线程的值
Thread[Thread-3,5,main] wait ......
Thread[Thread-2,5,main] wait ......
Thread[Thread-1,5,main] wait ......
Thread[Thread-2,5,main]------------>5050
Thread[Thread-3,5,main]------------>5050
2.很正常的结果,也是多数输出结果
Thread[Thread-1,5,main] wait ......
Thread[Thread-3,5,main] wait ......
Thread[Thread-2,5,main] wait ......
Thread[Thread-2,5,main]------------>5050
Thread[Thread-3,5,main]------------>5050
Thread[Thread-1,5,main]------------>5050
3.一种插曲输出结果
Thread[Thread-2,5,main] wait ......
Thread[Thread-2,5,main]------------>5050
Thread[Thread-3,5,main] wait ......
Thread[Thread-1,5,main] wait ......
Thread[Thread-1,5,main]------------>5050
Thread[Thread-3,5,main]------------>5050
Java 多线程 线程 --------------------编程问答-------------------- 请大侠帮忙解释下,第一种情况,确实存在这种结果,如何避免?
补充:Java , Java相关