最新消息:

三个线程,第一个线程输出连续的三个数,第二个线程再线程一输出的基础上再连续输出三个数,线程三和线程二一样

java 老鹰 279浏览 0评论


public class Run {

public static void main(String[] args) {
Object lock = new Object();
MyThread t1 = new MyThread(lock, 1, 1);
MyThread t2 = new MyThread(lock, 2, 1);
MyThread t3 = new MyThread(lock, 0, 1);
t1.start();
t2.start();
t3.start();
}
}

public class MyThread extends Thread {

private Object lock;

private int showNumPosition;

volatile private static int addNumber = 1;

volatile private static int circle = 0;

public MyThread(Object lock, int showNumPosition, int circle) {
super();
this.lock = lock;
this.showNumPosition = showNumPosition;
this.circle = circle;
}

public void run() {
try {
synchronized (lock) {
while (true) {
if (addNumber % 3 == showNumPosition) {
for(int i=0; i<3; i++) {
if(circle > 30) {
break;
}
System.out.println(Thread.currentThread() + "--" + circle);
circle++;
}
addNumber++;
lock.notifyAll();
if(circle >= 30) {
break;
}
} else {
lock.wait();
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

转载请注明:冯英胜的博客 » 三个线程,第一个线程输出连续的三个数,第二个线程再线程一输出的基础上再连续输出三个数,线程三和线程二一样

发表我的评论
取消评论
表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址