[Java] 纯文本查看 复制代码 package com.thread;
public class Test {
public static void main(String[] args) {
Demo d1 = new Demo();
Thread t1 = new Thread(d1,"第一组");
Thread t2 = new Thread(d1,"第二组");
Thread t3 = new Thread(d1,"第三组");
Thread t4 = new Thread(d1,"第四组");
t1.start();
t2.start();
t3.start();
t4.start();
}
}
//实现Runnable接口
class Demo implements Runnable{
private int num = 80;//学生人数,共享资源
@Override
public void run() {
String groupName = Thread.currentThread().getName();
while(true){
synchronized ("") {
if(num > 0){
try {
Thread.sleep(100);
System.out.println("编号为"+ num + "的学生被分到了" + groupName);
num--;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
} |