This page contains an archived post to the Java Answers Forum made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Artima Forums.
Message:
Multi threading problem
Posted by Anand Dubey on July 11, 2001 at 7:12 PM
I am trying to write an application that waits for 1 sec to execute incCount() and if this does not finish the main thread should go ahead without careing about the child thread. Problem with this code is -as callInCount() and run() are in the same object wait(1000) does not get the lock on the monitor because run being in the same object will not release the object monitor lock. and wait(1000) has to wait till run finishes. I have to use Runnable interface. Here is the code i am experimenting with. I have to use these type of concept while i am getting some data from database Thanks Anand public class mainclass implements Runnable { //private secclass sc = new secclass(); private int count = 0; int i = 0; void incCount() { for (int j=1; j<1000; j++) { for (int i=1; i<100001; i++) { if(i%100000==0&& j%100==0) { ++count; System.out.println(count +" "+(i)); } } } } public synchronized void run() { System.out.println("run started"); incCount(); notify(); System.out.println("value of i "+i); }
synchronized void callInCount() { try { Thread th = new Thread(this, "mythread"); th.start(); System.out.println("after start"); System.out.println(" thread name after start()-"+Thread.currentThread().toString()); System.out.println("before wait"); towait(); System.out.println(" i "+ i); //wait(8000); //mainclass.this.notify(); System.out.println("after wait"); } catch(Exception e){System.out.println("Exceptioncaught");} } void towait() { try { wait(1000); } catch(Exception e){System.out.println("Exceptioncaught");} System.out.println("thread name in to wait-" + Thread.currentThread().toString()); System.out.println("i in to wait-"+i); } public static void main(String[] arg) { mainclass ms = new mainclass(); ms.callInCount(); System.out.println("main ends"); } }
Replies:
|