Advertisement
synchronized(B ob) //Synchronized the access of B's object, ob.
{ //Synchronized block starts
ob.non_Synchronized_Method(); //Call to non-synchronized method of object, ob.
} //Synchronized block ends
Advertisement
//Java - A synchronized block
class B
{
public void meth()
{
for(int i=0;i<3;i++)
{
System.out.println(Thread.currentThread()+" " + i);
}
}
}
//Creating a class, A, which implements Runnable interface
class A implements Runnable
{
B obj;
A(B ob)
{
obj=ob;
}
public void run() //Entry point of the thread.
{
//A synchronized block
synchronized(obj) //synchronizing the object of B class
{
obj.meth(); //call to meth() is synchronized
}
}
public static void main(String... ar)
{
//Creating an object of class B
B b = new B();
//Creating an object of class A
A a1 = new A(ob);
A a2 = new A(ob);
Thread t1= new Thread(a1, "Thread1");
Thread t2= new Thread(a2, "Thread2"); //Calling Thread's constructor & passing the object
//of A class that implemented Runnable interface
//& the name of new thread.
//Starting the first thread
thread1.start();
//Starting the second thread
thread2.start();
}
}
Thread[Thread1,5,main] 0
Thread[Thread1,5,main] 1
Thread[Thread1,5,main] 2
Thread[Thread2,5,main] 0
Thread[Thread2,5,main] 1
Thread[Thread2,5,main] 2
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement