/*
需求:模拟三个老师同时发80份试卷 每个老师相当于一个线程。
*/
class Teacher implements Runnable//实现Runnable方法有助于解决资源共享问题
{
private int count=80;
Object obj = new Object();
public void run()//重写run方法
{
synchronized(obj)//加锁
{
for (;count>0 ;count-- )
{
System.out.println(Thread.currentThread().getName()+"发放第"+count+"份试卷");
}
}
}
}
class Test5
{
public static void main(String [] args)
{
Teacher tc = new Teacher();
Thread th1 = new Thread(tc,"teacher1");
Thread th2 = new Thread(tc,"teacher2");
Thread th3 = new Thread(tc,"teacher3");
th1.start();
th2.start();
th3.start();
}
} |
|