模拟3个老师同时发80份笔记, 每个老师相当于一个线程, 分别给三个线程命名为”张老师线程,林老师线程,李老师线程”,
* 1) 要求在控制台输出"xxx老师"在发第"xxx"份笔记
* 2) 如果要求最后一张试卷必须由”李老师线程”发出,请问应该怎么做?
public static void main(String[] args) throws InterruptedException {
new TeacherThread("张老师").start();
new TeacherThread("林老师").start();
new TeacherThread("李老师").start();
}
class TeacherThread extends Thread{
private static int num = 1;
public TeacherThread(String name) {
super(name);
}
@Override
public void run() {
while (true) {
synchronized (TeacherThread.class) {
if (num == 81) {
break;
}
if (num == 80) {
if (!("李老师").equals(getName())) {
continue;
}
}
System.out.println(getName() + "正在发" + num + "份笔记");
num++;
}
}
}
}
|