Java執行緒迴圈順序執行
阿新 • • 發佈:2019-02-20
遇到一個面試題需要3個執行緒順序執行,並迴圈10次,程式碼如下:
public class MyThread extends Thread {
private Object lock;
private String showChar;
private int showNumPosition;
private int printCount = 0;
volatile private 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 == 10 ) {
break;
}
} else {
lock.wait();
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public class Run {
public static void main(String[] args) {
Object lock = new Object();
MyThread a = new MyThread(lock, "A", 1);
MyThread b = new MyThread(lock, "B", 2);
MyThread c = new MyThread(lock, "C", 0);
a.start();
b.start();
c.start();
}
}
執行結果如下
ThreadName=Thread-0 runCount=1 A
ThreadName=Thread-1 runCount=2 B
ThreadName=Thread-2 runCount=3 C
ThreadName=Thread-0 runCount=4 A
ThreadName=Thread-1 runCount=5 B
ThreadName=Thread-2 runCount=6 C
ThreadName=Thread-0 runCount=7 A
ThreadName=Thread-1 runCount=8 B
ThreadName=Thread-2 runCount=9 C
ThreadName=Thread-0 runCount=10 A
ThreadName=Thread-1 runCount=11 B
ThreadName=Thread-2 runCount=12 C
ThreadName=Thread-0 runCount=13 A
ThreadName=Thread-1 runCount=14 B
ThreadName=Thread-2 runCount=15 C
ThreadName=Thread-0 runCount=16 A
ThreadName=Thread-1 runCount=17 B
ThreadName=Thread-2 runCount=18 C
ThreadName=Thread-0 runCount=19 A
ThreadName=Thread-1 runCount=20 B
ThreadName=Thread-2 runCount=21 C
ThreadName=Thread-0 runCount=22 A
ThreadName=Thread-1 runCount=23 B
ThreadName=Thread-2 runCount=24 C
ThreadName=Thread-0 runCount=25 A
ThreadName=Thread-1 runCount=26 B
ThreadName=Thread-2 runCount=27 C
ThreadName=Thread-0 runCount=28 A
ThreadName=Thread-1 runCount=29 B
ThreadName=Thread-2 runCount=30 C