simple multithreading - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

simple multithreading

fgstatusfgstatus Posts: 1Member
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.

[code]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();
}
}
}[/code]
Sign In or Register to comment.