Quantcast
Channel: Programmers Heaven Forums RSS Feed
Viewing all articles
Browse latest Browse all 2703

simple multithreading

$
0
0
Can anyone read the following code and see why I can't let 3 threads count to 60? Order in which they execute (increment to 20) is not important but most of the times I only see two of them do. The only condition is I have to use wait and notify to make it work.

class MyBetterThread extends Thread {
	  private static int count = 0;
	  private static boolean can_go = true;
	  private String name;	
	  public void incrementby(int j)throws InterruptedException {
		  synchronized (this) {
			  while (!can_go) {
				  wait();  // release the lock of this object
			  }
			  can_go = false;
			  for (int i = 1; i <= j; ++i) {  // try 5, 10, 20
				  count += 1;
				  System.out.println("Count from " + name + ": " + count);
			  }
			  can_go = true;
			  notify();
		  }
	   }
	   public MyBetterThread(String name) {   // constructor
	      this.name = name;
	   }
	   @Override
	   public void run() {
		   try {
			   incrementby(20);
		   } catch (InterruptedException e) {} 
	  }
}

class MyBetterThreadTest {
    public static void main(String[] args) {
        Thread[] mybetterthreads = {
           new MyBetterThread("Thread 1"),
           new MyBetterThread("Thread 2"),
           new MyBetterThread("Thread 3")
        };
        for (Thread t : mybetterthreads) {
           t.start();
        }
    }
}


Viewing all articles
Browse latest Browse all 2703

Trending Articles