You are here:

Java/thread synchronization

Advertisement


Question
Hii! 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
Hello,

Sorry for the late reply. I have been busy with personal issues.. Try this in your for -loop :
System.out.println("ThreadId:" + Thread.currentThread().getId() + ", TableObjectId:" + System.identityHashCode(this) + ", Output:" + n*i);

Take care..

Java

All Answers


Answers by Expert:


Ask Experts

Volunteer


henry joe

Expertise

I can confidently answer questions relating to JSE and JEE6 . Please no questions on JME.

Experience

I am experienced in JSE and JEE6

Education/Credentials
I am a BSEng graduate

©2016 About.com. All rights reserved.