三个线程同时进行,利用同步代码块(synchronized(lock))来处理数据,防止出现0和-1的情况。
class Distributionpaper implements Runnable
{
private int papers=80;
public Object lock=new Object();
public void run()
{
while(true)
{
synchronized(lock)
{
try
{
Thread.sleep(20);
}catch(Exception e){}
if(papers<=0)
{
break;
}
papers--;
System.out.println(Thread.currentThread().getName()+"分发第"+papers+"考卷");
}
}
}
}
public class DistributionpaperTest
{
public static void main(String[] args)
{
Distributionpaper teacher=new Distributionpaper();
new Thread(teacher,"第一个老师").start();
new Thread(teacher,"第二个老师").start();
new Thread(teacher,"第三个老师").start();
}
}