package MutileThread;
import java.util.concurrent.TimeUnit;
class Resource11 implements Runnable{
private int cnt = 0;
Object lock = new Object();
@Override
public void run()
{
while (cnt<20) // don't stop the thread
{
synchronized(lock)
{
System.out.println(String.format("Thread %s, cnt is %d",Thread.currentThread().getName(),cnt++));
if (cnt<20)
{
lock.notifyAll(); // before wait() !!!
}
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class RRun1 {
public static void main(String[]args) throws InterruptedException
{
Resource11 rRun1 = new Resource11();
Thread A = new Thread(rRun1,"A");
Thread B = new Thread(rRun1,"B");
A.start();
TimeUnit.SECONDS.sleep(2);
B.start();
}
}
两个线程交替打印奇偶数
最新推荐文章于 2021-05-23 22:55:14 发布