I am learning multi threading. I've written a program using synchronization to print table of 10 and 5 using two threads. While synchronized method is giving me expected result, synchronized block isn't. What am i doing wrong?
public class SynchronizationDemo {
public static void main(String[] args) {
Thread1 t=new Thread1(10);
Thread1 t1=new Thread1(5);
Thread thread1=new Thread(t);
Thread thread2=new Thread(t1);
thread1.start();
thread2.start();
}
//synchronized method
/*public static synchronized void printTable(int num) {
for (int i = 1; i <= 10; i++) {
System.out.println(num*i);
try {
Thread.sleep(1000);
}catch(InterruptedException ie){
ie.printStackTrace();
}
}
}*/
//synchronized block
public void printTable(int num)
{
synchronized(this){
for (int i = 1; i <= 10; i++) {
System.out.println(num*i);
try {
Thread.sleep(1000);
}catch(InterruptedException ie){
ie.printStackTrace();
}
}
}
}
}
class Thread1 implements Runnable{
int num;
Thread1(int num){
this.num=num;
}
@Override
public void run() {
new SynchronizationDemo().printTable(num);
}
}
Output of the code : 10 5 10 20 30 15 20 40 25 50 60 30 70 35 40 80 90 45 100 50
Expected output: 10 20 30 40 50 60 70 80 90 100 5 10 15 20 25 30 35 40 45 50