2つのスレッドの交互実行
1997 ワード
public class TwoThreadLock {
private static Object lock = new Object();
private static boolean flag = false;
public static void main(String[] args) {
Thread a = new Thread(){
public void run()
{
while(true)
{
synchronized(lock)
{
System.out.println("Thread1");
if(flag)
{
flag = false;
lock.notify();
try {
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
};
Thread b = new Thread(){
public void run()
{
while(true)
{
synchronized(lock)
{
System.out.println("Thread2");
if(!flag)
{
flag =true;
try {
lock.wait();
lock.notify();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
}
};
a.start();
b.start();
}
}