producer - consumer multithreading in Java -
i want write program using multithreading wait , notify methods in java.
program has stack (max-length = 5). producer generate number forever , put in stack, , consumer pick stack.
when stack full producer must wait , when stack empty consumers must wait.
problem runs once, mean once produce 5 number stops put run methods in while(true) block run nonstop able doesn't.
here tried far.
producer class:
package trail; import java.util.random; import java.util.stack; public class thread1 implements runnable { int result; random rand = new random(); stack<integer> = new stack<>(); public thread1(stack<integer> a) { this.a = a; } public synchronized void produce() { while (a.size() >= 5) { system.out.println("list full"); try { wait(); } catch (interruptedexception e) { e.printstacktrace(); } } result = rand.nextint(10); system.out.println(result + " produced "); a.push(result); system.out.println(a); this.notify(); } @override public void run() { system.out.println("producer started"); try { thread.sleep(10); } catch (interruptedexception e) { e.printstacktrace(); } while (true) { produce(); try { thread.sleep(100); } catch (interruptedexception e) { e.printstacktrace(); } } } }
and consumer:
package trail; import java.util.stack; public class thread2 implements runnable { stack<integer> = new stack<>(); public thread2(stack<integer> a) { this.a = a; } public synchronized void consume() { while (a.isempty()) { system.err.println("list empty" + + a.size()); try { wait(); } catch (interruptedexception e) { e.printstacktrace(); } } system.err.println(a.pop() + " consumed " + a); this.notify(); } @override public void run() { system.out.println("new consumer started"); try { thread.sleep(10); } catch (interruptedexception e) { e.printstacktrace(); } while (true) { consume(); } } }
and here main method:
public static void main(string[] args) { stack<integer> stack = new stack<>(); thread1 thread1 = new thread1(stack);// p thread2 thread2 = new thread2(stack);// c thread = new thread(thread1); thread b = new thread(thread2); thread c = new thread(thread2); a.start(); b.start(); c.start(); }
i think better understanding , dealing synchronisation in general if try separate 3 things mixed:
task going actual job. names classes
thread1
&thread2
misleading. not thread objects, jobs or tasks implementing runnable interface givingthread
objects.thread object creating in main
shared object encapsulates synchronised operations/logic on queue, stack etc. object shared between tasks. , inside shared object take care of add/remove operations (either synchronized blocks or synchronized methods). (as pointed out already), synchronization done on task (i.e. each task waits , notifies on own lock , nothing happens). when separate concerns, i.e. let 1 class 1 thing become clear problem.
Comments
Post a Comment