Monday, May 25, 2020

Thread wait coding example


package test; import java.util.*; class Counter { int count; public void add() { count++; System.out.println("add : " + count); } public void get() { System.out.println("get : " + count); } } public class Test { public static void main(String args[]) throws InterruptedException { Counter c = new Counter(); Thread t1 = new Thread(() -> { for (int i = 0; i < 10; i++) { synchronized (c) { c.add(); try { c.notify(); c.wait(); Thread.sleep(1000); } catch (InterruptedException ex) { ex.printStackTrace(); } } } } ); Thread t2 = new Thread(() -> { for (int i = 0; i < 10; i++) { c.get(); synchronized (c) { try { c.notify(); c.wait(); Thread.sleep(1000); } catch (InterruptedException ex) { ex.printStackTrace(); } } } } ); Thread t3 = new Thread(() -> { for (int i = 0; i < 10; i++) { c.get(); synchronized (c) { try { c.notify(); c.wait(); Thread.sleep(1000); } catch (InterruptedException ex) { ex.printStackTrace(); } } } } ); t1.start(); t2.start(); t3.start(); t1.join(); t2.join(); t3.join(); System.out.println("after waiting count :" + c.count); } }