今天复习了下Object的wait,notify相关的方法,记录下
public class TestO {
static Cat[] arr = new Cat[]{new Cat(), new Cat(), new Cat(), new Cat()};
static AtomicInteger counter = new AtomicInteger(0);
public synchronized void cc() {
System.out.println(Thread.currentThread().getName() + " enter TestO");
Cat cat = get();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
this.wait();
System.out.println(Thread.currentThread().getName()+" notify");
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " end");
}
Cat get() {
return arr[counter.getAndIncrement() & (arr.length - 1)];
}
public static void main(String[] args) {
TestO test = new TestO();
new MyThread(test).start();
new MyThread(test).start();
new MyThread(test).start();
new MyThread(test).start();
new MyThread(test).start();
new MyThread(test).start();
new MyThread(test).start();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String cmd = scanner.next();
synchronized (test) {
if (cmd.equals("1")) {
test.notify();
} else {
test.notifyAll();
}
}
}
}
static class MyThread extends Thread {
TestO object;
public MyThread(TestO o) {
this.object = o;
}
@Override
public void run() {
object.cc();
}
}
}
- wait notify notifyAll都要在synchronized 里面执行
- wait方法会使线程释放锁,sleep不会
- wait方法实际上是将线程移入对象的锁等待池,notify和notifyAll将线程移入对象的锁竞争池
- 根据测试结果,notify会将线程按照FIFO的原则将线程从锁等待池移入竞争池
网友评论