几个线程,循环打印1 - 100
public static void main(String[] args) throws UnsupportedEncodingException, InterruptedException {
new Main().printfTo100();
}
public boolean isStop = false;
public class Model {
private int count = 0;
private Model next;
public void setCount(int count) {
this.count = count;
}
public Model getNext() {
return next;
}
public void setNext(Model model) {
this.next = model;
}
public int getCount() {
return count;
}
}
private void printfTo100() throws InterruptedException {
// 创建数据描述
Model modelA = new Model();
Model modelB = new Model();
Model modelC = new Model();
// 形成一个数据循环
modelA.setNext(modelB);
modelB.setNext(modelC);
modelC.setNext(modelA);
// 创建线程
MyThread thradA = new MyThread(modelA);
MyThread thradB = new MyThread(modelB);
MyThread thradC = new MyThread(modelC);
// 启动线程
thradA.start();
thradB.start();
thradC.start();
Thread.sleep(1000);
synchronized (modelA) {
modelA.notify();
}
}
public class MyThread extends Thread {
private Model model;
public MyThread(Model model) {
this.model = model;
}
public void run() {
try {
// 忽略异常处理
synchronized (model) {
while (!isStop) {
// 每个线程创建的时候 先wait
model.wait();
if (isStop) {
break;
}
// 被唤醒之后,打印对应的数字
System.out.println(model.getCount());
if (model.getCount() >= 100) {
Main.this.stop(model);
break;
}
// 下一个线程,加上1
model.getNext().setCount(model.getCount() + 1);
// 通知下一个线程开始工作
synchronized (model.getNext()) {
model.getNext().notify();
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void stop(Model model) {
isStop = true;
Model temp = model.next;
while (temp != model) {
synchronized (temp) {
temp.notify();
}
temp = temp.next;
}
}