Thread communication: wait, wake up
Object method | These methods can only be called when they have resources |
---|---|
notify | Wake up a thread. Wake up is not executed immediately, but wait for CPU allocation |
wait | Wait, release lock, do not occupy CPU resources |
notifyAll | Wake up all waiting threads |
Key points: effective utilization of resources
One for production and one for consumption; one for reproduction and one for consumption
Take hot dry noodles as an example (problems of producers and consumers):
class Hot and dry noodles { int isOK = 0; } class Producer implements Runnable { //Hot dry noodles m; public Producer(Hot and dry noodles m) { this.m = m; } public void Make face() { try { synchronized (m) { if (m.isOK > Desk.BUFFER_MAX) { System.out.println("+Do it when you need to"); m.wait(); System.out.println("+Start doing"); } m.isOK++; System.out.println("+Make face" + m.isOK); m.notify(); } } catch (Exception e) { e.printStackTrace(); } } public void run() { while (true) { try { Thread.sleep(Desk.Face time); } catch (InterruptedException e) { e.printStackTrace(); } //Make face (); / / production face } } } class Consumer implements Runnable { //Hot dry noodles m; public Consumer(Hot and dry noodles m) { this.m = m; } public void Eating noodles() { try { synchronized (m) {// #Lock face objects if (m.isOK <= 0) { System.out.println("------Equal surface"); m.wait();// Wait, release lock System.out.println("------There are faces."); } System.out.println("------Eating noodles:" + m.isOK); m.isOK--; m.notify();// Wake up another thread, but both threads wait for CPU execution } } catch (Exception e) { e.printStackTrace(); } } public void run() { while (true) { try { Thread.sleep(Desk.Eating time); } catch (InterruptedException e) { e.printStackTrace(); } //Eat noodles (); } } } class Desk {// In order to manage objects and simulate real scenes, you can not public static final int Face time = 100; public static final int Eating time = 100; public static final int BUFFER_MAX = 1; //Hot dry surface msg = new hot dry surface (); //Producer m = new producer (msg); //Consumer c = new consumer (msg); Thread t1 = new Thread(m); // Producer thread Thread t2 = new Thread(c); // Consumer thread public void fn() { t1.start(); t2.start(); } } public class Producer consumer issues { public static void main(String[] args) { Desk d = new Desk(); d.fn(); } }