一、 有4個線程A、B、C、D,分別打印1、2、3、4,請同時啓動他們,可是要求按照1234的順序輸出結果。ide
public class TestABCThread3 {this
private Object lock = new Object();spa
private int count;線程
public static void main(String[] args) {it
TestABCThread3 abc = new TestABCThread3();io
new Thread(abc.new Run("C", 3)).start();class
new Thread(abc.new Run("D", 4)).start();thread
new Thread(abc.new Run("A", 1)).start();im
new Thread(abc.new Run("B", 2)).start();d3
}
class Run implements Runnable {
private String _name = "";
private int _threadNum;
public Run(String name, int threadNum) {
_name = name;
_threadNum = threadNum;
}
@Override
public void run() {
synchronized (lock) {
while (true) {
if (count % 4 == _threadNum - 1) {
System.out.println("Thread-Name:" + _name+",No:"+this._threadNum);
count++;
lock.notifyAll();
break;
} else {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
}