synchronized (object reference expression) { //code inside synchronized block }
class SyncTable{ void printTable(int temp){ synchronized(this) { for(int i=1;i<=5;i++){ System.out.println(Thread.currentThread().getName() + ": " +temp + "*"+ i + " value: " + i*temp); try{ Thread.sleep(400); } catch(Exception e){ System.out.println(e); } } } } } class MyThread1 extends Thread{ SyncTable synctable; MyThread1(SyncTable synctable){ this.synctable=synctable; } public void run(){ synctable.printTable(5); } } class MyThread2 extends Thread{ SyncTable synctable; MyThread2(SyncTable synctable){ this.synctable=synctable; } public void run(){ synctable.printTable(9); } } public class Main{ public static void main(String arg[]){ SyncTable synctable = new SyncTable(); //only one object MyThread1 thread1=new MyThread1(synctable); MyThread2 thread2=new MyThread2(synctable); thread1.start(); thread2.start(); } }
Output:
Thread-1: 9*1 value: 9
Thread-1: 9*2 value: 18
Thread-1: 9*3 value: 27
Thread-1: 9*4 value: 36
Thread-1: 9*5 value: 45
Thread-0: 5*1 value: 5
Thread-0: 5*2 value: 10
Thread-0: 5*3 value: 15
Thread-0: 5*4 value: 20
Thread-0: 5*5 value: 25
Police Colony
Patna, Bihar
India
Email:
Post your comment