创建两个Runnable,其中一个的run()方法启动并调用wait(),第二个Runnable中run()方法在一定的几秒之后,为第一个任务调用notify(),从而使得第一个Runnable能显示一条信息,用Executor来测试。
参考例子:点击打开链接
原博主第一个未改的例子中main线程new了一个RunnableWait对象,但是在RunnableNotify线程类中又new了一个新的对象,所以才会两个obj对象不一样
wait() notify(),notifyAll()三个方法是基于对象的。同时,在wait()等待期间,锁被释放,因此,其它线程得以执行
我修改的:
//还有一种不使用静态方法的办法就是在线程任务类中的构造器里构造
class TestRun{}
class RunnableWait implements Runnable{
public static TestRun testRun = new TestRun();//首先加载RunnableWait,生成一个静态实例
@Override
public void run() {
synchronized (testRun)
{
System.out.println(Thread.currentThread()+"开始等待" + testRun);
try
{
testRun.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread()+"等待结束!" + testRun);
}
}
public static TestRun getLock() //返回对象
{
return testRun;
}
}
class RunnableNotify implements Runnable{
private TestRun testRun = RunnableWait.getLock();
@Override
public void run()
{
synchronized (testRun)
{
try
{
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread()+"唤醒rwait!"+testRun+"/ "+ testRun);
testRun.notifyAll();
System.out.println(Thread.currentThread()+"唤醒结束!" + testRun);
}
}
}
public class ExecutorMain {
public static void main(String[] args) {
ExecutorService exe =Executors.newCachedThreadPool();
exe.execute(new RunnableWait());
exe.execute(new RunnableNotify());
exe.shutdown();
}
}