notify示例
public class NotifySample {
public static void main(String[] args) throws InterruptedException
{
notifyTest();
notifyTest2();
notifyTest3();
}
private static void notifyTest() throws InterruptedException
{
MyThread[] arrThreads = new MyThread[3];
for (int i = 0; i < arrThreads.length; i++)
{
arrThreads[i] = new MyThread();
arrThreads[i].id = i;
arrThreads[i].setDaemon(true);
arrThreads[i].start();
}
Thread.sleep(500);
for (int i = 0; i < arrThreads.length; i++)
{
synchronized(arrThreads[i])
{
arrThreads[i].notify();
}
}
}
private static void notifyTest2() throws InterruptedException
{
MyRunner[] arrMyRunners = new MyRunner[3];
Thread[] arrThreads = new Thread[3];
for (int i = 0; i < arrThreads.length; i++)
{
arrMyRunners[i] = new MyRunner();
arrMyRunners[i].id = i;
arrThreads[i] = new Thread(arrMyRunners[i]);
arrThreads[i].setDaemon(true);
arrThreads[i].start();
}
Thread.sleep(500);
for (int i = 0; i < arrMyRunners.length; i++)
{
synchronized(arrMyRunners[i])
{
arrMyRunners[i].notify();
}
}
}
private static void notifyTest3() throws InterruptedException
{
MyRunner runner = new MyRunner();
Thread[] arrThreads = new Thread[3];
for (int i = 0; i < arrThreads.length; i++)
{
arrThreads[i] = new Thread(runner);
arrThreads[i].setDaemon(true);
arrThreads[i].start();
}
Thread.sleep(500);
synchronized(runner)
{
runner.notifyAll();
}
}
}
class MyThread extends Thread
{
public int id = 0;
public void run()
{
System.out.println("第" + id + "个线程准备休眠5分钟。");
try
{
synchronized(this)
{
this.wait(5*60*1000);
}
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
System.out.println("第" + id + "个线程被唤醒。");
}
}
class MyRunner implements Runnable
{
public int id = 0;
public void run()
{
System.out.println("第" + id + "个线程准备休眠5分钟。");
try
{
synchronized(this)
{
this.wait(5*60*1000);
}
}
catch(InterruptedException ex)
{
ex.printStackTrace();
}
System.out.println("第" + id + "个线程被唤醒。");
}
}
|
|