1、 有4个线程A、B、C、D,分别打印1、2、3、4,请同时启动他们,但是要求按照1234的顺序输出结果。
public class TestABCThread3 {
private Object lock = new Object();
private int count;
public static void main(String[] args) {
TestABCThread3 abc = new TestABCThread3();
new Thread(abc.new Run("C", 3)).start();
new Thread(abc.new Run("D", 4)).start();
new Thread(abc.new Run("A", 1)).start();
new Thread(abc.new Run("B", 2)).start();
}
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();
}
}
}
}
}
}
}