public static void main(String[] args) {
Demo_2Runnable d = new Demo_2Runnable();
Thread t1 = new Thread(d, "第一组");
Thread t2 = new Thread(d, "第二组");
Thread t3 = new Thread(d, "第三组");
Thread t4 = new Thread(d, "第四组");
t1.start();
t2.start();
t3.start();
t4.start();
}
public class Demo_2Runnable implements Runnable {
private Object object = new Object();
private int number = 80;
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
synchronized (object) {
if (number > 0) {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (number == 4) {
System.out.println("编号为4的学生被分到第一组");
number--;
} else if (number == 16) {
System.out.println("编号为16的学生被分到第四组");
number--;
} else if (number == 17) {
System.out.println("编号为17的学生被分到第四组");
number--;
} else {
System.out.println("编号为" + number-- + "的学生被分在"
+ Thread.currentThread().getName());
}
} else {
break;
}
}
}
}
}
|