notifyとwaitの例では、2つのスレッドが交互に1つの変数を10に加算します.
(1)スレッド1はプラス1を開始し,次いでwait 1ミリ秒(2)のこのミリ秒に1回スレッド2を実行し,waitは(3)スレッド1を1ミリ秒待って自動的にリソースのロックを取得し,スレッド2を起動して準備状態(4)スレッド1がロックを解放していないため,ループを継続し,次いで、wait 1ミリ秒(5)このとき、スレッド2は1回実行され、waitは、ループを終了するまで(3〜5)繰り返すことができる.
package com.thread;
public class TwoThread
{
public static void main(String[] args)
{
Counter c = new Counter();
new Thread(new ThreadOne(c)," 1").start();
new Thread(new ThreadTwo(c)," 2").start();
}
}
class ThreadOne implements Runnable
{
Counter c;
public ThreadOne(Counter c)
{
this.c = c;
}
/**
*
*/
public void run()
{
synchronized (c)
{
while (c.value < 10)
{
c.value++;
System.out.println(Thread.currentThread().getName() + " value 1,value = "
+ c.value);
try
{
c.wait(1);// c , 2 ( 2 wait )
c.notify();// 1 , 2 , 2 , wait(1):
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}
class ThreadTwo implements Runnable
{
Counter c;
public ThreadTwo(Counter c)
{
this.c = c;
}
/**
*
*/
public void run()
{
synchronized (c)
{
while (c.value < 10)
{
c.value++;
System.out.println(Thread.currentThread().getName() + " value 1,value = "
+ c.value);
try
{
c.wait();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
}
class Counter
{
int value;
/**
* @return value
*/
public int getValue()
{
return this.value;
}
}