• Post Reply Bookmark Topic Watch Topic
  • New Topic

Clarification on Thread  RSS feed

 
Ramkumar Venkat
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Guys,
I have formed a "pseudo-code" of possible sequence of operation, when the code below executes.Please correct me if my understanding is wrong.
// Pseudo-code
if(The thread is first to access test() method) {
1: gets lock on the "t"(Object of type Test)
execute the method test()
if(finished executing test()) {
release lock;
call notify()/notifyAll() on the object "t", which inturn informs the thread scheduler that the object "t" is free.
}
}
else {
call wait() on object "t"; // wait(), I believe, informs the thread //scheduler that the current thread is waiting for the object "t"
goes to not runnable state;
When invoked by thread scheduler, thread goes to runnable state GOTO 1
}

// actual code

class MyThread extends Thread {
Test t;
public MyThread(String msg, Test t) {
super(msg);
this.t = t;
}

public void run() {
System.out.println(getName());
t.test();
}
}

public class Test {

synchronized void test() {
System.out.println("test called");
}

public static void main(String[] args) {
Test t = new Test();
new MyThread("Thread one",t).start();
new MyThread("Thread two",t).start();


}
}
 
Ellen Zhao
Ranch Hand
Posts: 581
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ramkumar,
I modifed the run() method in your code, but not sure whether there is any error else there. Usually in the run() method, you have to catch the InterruptedException.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ellen - no, you don't need to catch an InterruptedException unless you call another method which can throw InterruptedException - such as Thread.sleep() or wait() (in Object). Since neither of these is called in the code here, there's no need for the try/catch here.
Ramkumar - well, your pseudocode and actual code don't match up very well. The pseudocode talks about wait() and notify(), which are never used in your code. Actually I think the real code is better than the pseudocode here - there's no real need for wait() and notify() here. What you seem to want (making other threads wait if on thread is already running the t.test() method) is already accomplished simply by declaring test() to be synchronized, as shown. So, your code looks fine, but the pseudocode looks strange. If you have further questions, perhaps you should explain what it the actual purpose of the code.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!