//Producer-Consumer Inter-thread communication //Table.java public class Table { private String obj; private boolean empty = true; public synchronized void put(String obj) { if(!empty) { try { wait(); }catch(InterruptedException e) { e.printStackTrace(); } } this.obj = obj; empty = false; System.out.println(Thread.currentThread().getName()+" has put "+obj); notify(); } public synchronized void get() { if(empty) { try { wait(); }catch(InterruptedException e) { e.printStackTrace(); } } empty = true; System.out.println(Thread.currentThread().getName()+" has got "+obj); notify(); } public static void main(String[] args) { Table table = new Table(); Runnable p = new Producer(table); Runnable c = new Consumer(table); Thread pthread = new Thread(p, "Producer"); Thread cthread = new Thread(c, "Consumer"); pthread.start(); cthread.start(); try{ pthread.join(); cthread.join(); } catch(InterruptedException e){ e.printStackTrace(); } } } /////////////Producer.java public class Producer implements Runnable { private Table table; public Producer(Table table) { this.table = table; } public void run() { java.util.Scanner scanner = new java.util.Scanner(System.in); for(int i=1; i <= 5; i++) { System.out.println("Enter text: "); table.put(scanner.next()); try{ Thread.sleep(1000); } catch(InterruptedException e){ e.printStackTrace(); } } } } ///////////Consumer.java public class Consumer implements Runnable { private Table table; public Consumer(Table table) { this.table = table; } public void run() { for(int i=1; i <= 5; i++){ table.get(); } } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter