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?