Win a copy of Java Concurrency Live Lessons this week in the Threads forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Help using threads synch  RSS feed

 
cornel jew
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all
I have a few questions regarding threads.
When creating your thread eg
class MyThread extends Thread
{
public void run()
{
//i want to call other synchronized methods from other objects here which will print something
Test t = new Test();
t.myMethod();//if its the right way to do it
}
public class Test
{
public synchronized myMethod()
{//print something here
//with a for loop x times
}
public static void main(String [] args)
{
MyThread mt = new MyThread();
MyThread mt1 = new MyThread();
MyThread mt2 = new MyThread();
mt.start();
mt1.start();
mt2.start();
}
What will happen if your thread access the myMethod() will it acces the method and print it x times in the loop b4 mt1 start,cos the
method is synch, or will mt1 and mt2 start intermixed.
This is the way i understand synchronized methods the method is locked so the other threads in the que must wait until the first
thread finish, meaning to print out x times b4 the others can enter the method.
I have run a test program ,but the output is mixed especially when the loop count is big, but smaller loops gives me right output.
Thanks for any help
Cornel
 
Anthony Villanueva
Ranch Hand
Posts: 1055
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your MyThread objects are not accessing a single Test object in a multi-threaded manner; rather, each MyThread has an object lock on its own Test object.

Each Strider object is running on its own, well, thread, while two Threads are accessing the single Runner object in a multi-threaded manner. Can you see the difference?
[ August 06, 2002: Message edited by: Anthony Villanueva ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!