You are here:

Java/thread synchronization

Advertisement


Question
Hi sir! my doubt is on thread synchronization.
when a thread is accesing a method which is synchronized that method should not  be available to any other thread until the first thread completes execution.
But below code not doing so.
you please read and clear my doubts.
------------------------------------------------------------------
class Table
{
synchronized void printTable(int n)
{
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try
{
Thread.sleep(500);
}
catch(Exception ie)
{
System.out.println(ie);
}
}
}
}
class MyThread1 extends Thread
{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
}
class MyThread2 extends Thread
{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
}
class synchronization2
{
public static void main(String args[])
{
MyThread1 t1=new MyThread1(new Table());
MyThread2 t2=new MyThread2(new Table());
t1.start();
t2.start();
}
}
------------------------------------------------------------------
Expected out put:
5
10
15
20
25
100
200
300
400
500
but the actual output is
5
100
200
10
300
15
400
20
500
25
------------------------------------------------------------------
my doubts:
1)why it is not giving expected output?
2)what is the mistake in the programme?
2)what can i do to get the expected out put?

Answer
1. Since printTable is an instance method, synchronization only happens on invocations of that method for the same instance.
2. You create a different instance of Table() for each thread
3. You can create an instance of Table and pass that same instance to each thread. Note that it might be possible that MyThread2 executes before MyThread1.

Java

All Answers


Answers by Expert:


Ask Experts

Volunteer


Artemus Harper

Expertise

I have a Masters in computer science. I can answer questions on core J2SE, swing and graphics. Please no questions about JSP or J2ME.

Experience

I have experience in Core Java, good background in Java swing/gui, some experience with JNI, Java reflection. Some experience in bio-informatics. Basics in c++ and c#

Organizations
Washington State University

Education/Credentials
MS in Computer Science from Washington State University and a BS in Mathematics and Computer Science from Central Washington University.

©2016 About.com. All rights reserved.