正常的情况下,线程在运行时多个线程之间执行任务的时机是无序的。可以通过改造代码的方式使它们运行具有有序性。
public class MyThread extends Thread {
private Object lock;
private String showChar;
private int showNumPosition;
private int printCount = 0; //统计打印了几个字母
private volatile static int addNumber = 1;
public MyThread(Object lock, String showChar, int showNumPosition) {
super();
this.lock = lock;
this.showChar = showChar;
this.showNumPosition = showNumPosition;
}
@Override
public void run() {
try {
synchronized (lock) {
while (true) {
if (addNumber % 3 == showNumPosition) {
System.out.println("ThreadName="
+ Thread.currentThread().getName()
+ ",runCount=" + addNumber + " " + showChar);
lock.notifyAll();
addNumber++;
printCount++;
if (printCount == 3) {
break;
}
} else {
lock.wait();
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Run { public static void main(String[] args) throws InterruptedException { Object lock = new Object(); MyThread a = new MyThread(lock, "AA", 1); MyThread b = new MyThread(lock, "BB", 2); MyThread c = new MyThread(lock, "CC", 0); a.start(); b.start(); c.start(); }}
ThreadName=Thread-0,runCount=1 AA ThreadName=Thread-1,runCount=2 BB ThreadName=Thread-2,runCount=3 CC ThreadName=Thread-0,runCount=4 AA ThreadName=Thread-1,runCount=5 BB ThreadName=Thread-2,runCount=6 CC ThreadName=Thread-0,runCount=7 AA ThreadName=Thread-1,runCount=8 BB ThreadName=Thread-2,runCount=9 CC |