最近要找工作,又把之前多线程的东西捞出来看看。
public class testOptional {
public static class Wait {
private volatile Integer counter = 0;
private String name = null;
public Wait(int counter, String name) {
this.counter = counter;
this.name = name;
}
public synchronized void doSomthing() {
System.out.println(Thread.currentThread().getName() + "start");
int tempcounter = --counter;
if (tempcounter <= 0) {
// customizedNotifyAll();
notify();
} else {
if (tempcounter > 0) {
try {
System.out.println(Thread.currentThread().getName() + "-<" + name + tempcounter + ">" + "will invoke WAIT()");
wait();
} catch (InterruptedException e) {
e.printStackTrace();
notifyAll();
}
System.out.println(Thread.currentThread().getName() + "-<" + name + tempcounter + ">" + "has been ACTIVED");
}
}
}
public void customizedNotifyAll() {
notifyAll();
System.out.println(Thread.currentThread().getName() + "-<" + name + counter + ">" + "::" + "INVOKED NOTIFYALL() AND FINISHED");
}
}
static class TestThread implements Runnable {
private Wait wait;
public TestThread(Wait wait) {
this.wait = wait;
}
public void run() {
wait.doSomthing();
}
}
public static void main(String[] args) throws InterruptedException {
Wait wait = new Wait(4, "test");
Thread testThread1 = new Thread(new TestThread(wait));
Thread testThread2 = new Thread(new TestThread(wait));
Thread testThread3 = new Thread(new TestThread(wait));
Thread testThread4 = new Thread(new TestThread(wait));
testThread1.start();
Thread.sleep(10);
testThread2.start();
Thread.sleep(10);
testThread3.start();
Thread.sleep(10);
testThread4.start();
}
}
代码是从网上一人的博客上改的,原代码有些问题
附上运行结果
notifyAll()
notify()