1.4 wait() 与 notify
例如消息队列生成和消费消息时候,可以用 wait (), notify 通知对方
wait 和 notify 必须在 synchronized方法里。
1) wait
释放当前线程的锁,线程进入等待状态,直到其他线程调用该对象的notify
2) notify
其他随机一个线程对应的等待状态解除。可以竞争当前锁。如果要解除所有解除线程的等待状态使用 notifyAll
package concurrent; public class MyQueue { private String[] data = new String[10]; private int size = 0; private int getInd = 0; private int putInd = 0; public synchronized void put(String ele) throws InterruptedException { if (size == 10) { wait(); put(ele); } else { size++; data[putInd++] = ele; if (putInd == data.length) putInd = 0; System.out.println("produce " + ele); notify(); } } public synchronized void get() throws InterruptedException { if (size == 0) { wait(); get(); } else { size--; String consume = data[getInd++]; if (getInd == data.length) getInd = 0; System.out.println("consume " + consume); notify(); } } }
package concurrent; public class ConsumerThread extends Thread{ private final MyQueue myQueue; public ConsumerThread(MyQueue myQueue) { this.myQueue = myQueue; } @Override public void run() { while (true) { try { myQueue.get(); } catch (InterruptedException e) { throw new RuntimeException(e); } } } }
package concurrent; public class ProducerThread extends Thread { private final MyQueue myQueue; private int index = 1; public ProducerThread(MyQueue myQueue) { this.myQueue = myQueue; } @Override public void run() { while (true) { try { if (index == 10) index = 1; String putStr = "data" + index; myQueue.put(putStr); index++; } catch (InterruptedException e) { throw new RuntimeException(e); } } } }
package concurrent; public class Main { public static void main(String[] args) { MyQueue myQueue = new MyQueue(); new ConsumerThread(myQueue).start(); new ProducerThread(myQueue).start(); } }