Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I am showing how I fixed the producer-consumer problem. I have using different way then you. I think this will help you..</p> <p>And the to make any block or method synchronized their are some condition :</p> <p>synchronized methods prevent more than one thread from accessing an object's critical method code simultaneously.</p> <p>You can use the synchronized keyword as a method modifier, or to start a synchronized block of code.</p> <p>To synchronize a block of code (in other words, a scope smaller than the whole method), you must specify an argument that is the object whose lock you want to synchronize on.</p> <p>While only one thread can be accessing synchronized code of a particular instance, multiple threads can still access the same object's unsynchronized code.</p> <p>static methods can be synchronized, using the lock from the java.lang.Class instance representing that class.</p> <p>All three methods—wait(), notify(), and notifyAll()<strong>—must be</strong> called <strong>from within a synchronized context!</strong> A thread invokes wait() or notify() on a particular object, and the thread must currently hold the lock on that object.</p> <pre><code>class P implements Runnable{ Data d; P(Data d){ this.d = d; new Thread(this,"Producer").start(); } public void run(){ for(int i=0; i&lt;=20; i++){ d.set(i); System.out.println("put -&gt; "+i); } } } class C implements Runnable{ Data d; C(Data d){ this.d = d; new Thread(this,"Consumer").start(); } public void run(){ for(int i=0; i&lt;=20; i++){ int n = d.get(); System.out.println("get -&gt; "+n); } } } class Data{ int n; boolean valueset=false; synchronized void set(int n){ if(valueset){ try{ wait(); }catch(Exception e){ System.out.println("set -&gt; Exception "+e); } } this.n = n ; valueset=true; notify(); } synchronized int get(){ if(!valueset){ try{ wait(); }catch(Exception e){ System.out.println("get -&gt; Exception "+e); } } valueset=false; notify(); return n ; } } class PC{ public static void main(String[] args){ Data d = new Data(); new P(d); new C(d); } } </code></pre> <p>You can download solution of producer consumer from here : </p> <p><a href="https://www.mediafire.com/?52sa1k26udpxveu" rel="nofollow">https://www.mediafire.com/?52sa1k26udpxveu</a></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload