Problem with java semaphore -
i new java , trying feel of language following example.can tell why following program shows:
calling prod calling cons import java.util.concurrent.*; public class trial5 { static public void main(string[] arg){ new prod(); new cons(); } } class q { static semaphore semc = new semaphore(0); static semaphore semp = new semaphore(1); static int q[]; } class cons implements runnable{ thread t; cons () { system.out.println("calling cons"); thread t = new thread(); t.start(); } public void run () { system.out.println("running semc"); try { system.out.println ("waiting data.acquiring semc"); q.semc.acquire (); if(q.q[0] != 0) { system.out.println(q.q[0]); q.q[0] = 0; } else { wait (); } system.out.println ("releasing semc"); q.semc.release (); } catch (exception e) { system.out.println (e.getmessage()); } } } class prod implements runnable { thread t; prod () { system.out.println ("calling prod"); t = new thread (); t.start (); } public void run() { system.out.println ("running semp"); try { system.out.println ("waiting data.acquiring semp"); q.semp.acquire (); if (q.q[0] == 0) { system.out.println ("setting value semp"); q.q[0] = 10; } else { thread.sleep(100); } system.out.println ("releasing semp"); q.semp.release (); } catch (exception e) { system.out.println (e.getmessage()); } } }
your problem isn't semaphore, it's threads. run method not executing because you're instantiating new instances of thread have no idea classes you've created , running rather doing classes you've created. run methods never getting called.
specifically, lines this:
thread t = new thread(); t.start(); have no reference classes contained in. create new thread object has default run method , start it.
this site has examples of how threads run (either through extending thread or implementing runnable). you're going have restructure code work, though. although might work change lines read
thread t = new thread(this); that's bad idea since you'd passing object value while constructor still running. better idea have main method construct each object , use them start threads running.
Comments
Post a Comment