0

I am working on an assignment to make three threads access the same object and print the name of the thread currently working on that object. Given below is the code

public class ThreadOne{
    public static void main(String args[]){
        Test obj=new Test();
        new threads(obj);
    }
}
class Test{
    public synchronized void message(Thread t){
        System.out.println(t.getName());
    }
}
class Threads implements Runnable{
    Thread t1,t2,t3;
    public void run(){
    }
    public threads(test obj){
        t1=new Thread(){
            public void run(){
                obj.message(t1);
            }
        };
        t2 = new Thread() {
            public void run() {
                obj.message(t2);
            }
        };
        t3 = new Thread() {
            public void run() {
                obj.message(t3);
            }
        };
        t1.start();
        t2.start();
        t3.start();
    }
}   

But from the output the third thread is accessing the object before the second thread, what I want is the threads to access the object in a synchronized manner, that is; the object should be accessed in the manner Thread-0 -> Thread-1 -> Thread-2

What changes in the code should I make to implement this?

QuickSilver
  • 3,915
  • 2
  • 13
  • 29

1 Answers1

5

synchronized does not control the order at all. It only ensures that no two threads can enter it at the same time.

If you want an explicit order of 1, 2, 3, why even have threads in the first place? Threading is used to execute code in parallel, not sequentially.

Anyways, you could do t1.join(); directly after t1.start(). That would explicitly wait until the first thread is done, before you execute t2.start(). Then also do t2.join(); for the same reason. So:

t1.start();
t1.join();
t2.start();
t2.join();
t3.start();

You could also have a wait and notify system. Or employ more complex structures to realizes the order-dependency.

Zabuzard
  • 25,064
  • 8
  • 58
  • 82