我现在对线程的wait(),notify()机制还是似懂非懂。先贴代码:
package com.lbr.testthread;
public class TestThread {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread t1 = new TestThread().new MyThread();
MyThread t2 = new TestThread().new MyThread();
t1.o = new Object();
t2.o = t1.o;
t1.start();
t2.start();
synchronized (t1.o) {
t1.o.notifyAll();
}
}
class MyThread extends Thread {
public Object o = null;
public void run() {
// TODO Auto-generated method stub
super.run();
try {
synchronized (o) {
System.out.println(Thread.currentThread().getName()+"锁住了");
o.wait();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("执行完毕" + Thread.currentThread().getName());
}
}
}
我想让这两个线程一开始都进入等待状态,当我执行nofityAll()的时候就让他们继续运行。
但是运行结果是:
Thread-0锁住了
Thread-1锁住了
也就是说两线程都进入了等待状态却没有被唤醒,求教哪里错了?
------解决思路----------------------
因为你的notifyAll();在wait之前就已经执行了,你可以延迟几秒再执行试试
------解决思路----------------------
synchronized?(o)?{
????????????????????System.out.println(Thread.currentThread().getName()+"锁住了");
????????????????????o.wait();
????????????????}
线程内部的代码为何要加锁呢?线程内部本来就是单线程的,
------解决思路----------------------
MyThread t1 = new TestThread().new MyThread();
MyThread t2 = new TestThread().new MyThread();
t1.o = new Object();
t2.o = t1.o;
t1.start();
t2.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (t1.o) {
t1.o.notifyAll();
}