In this tutorial how perform Synchronisation in Multiple Threads in Core Java is shown.
Code:
Thread5.java
class MyThread extends Thread
{
int count=0;
MyThread(String name)
{
setName(name);
}
synchronized void getCounterThread()
{
count++;
System.out.println(“Counter “+count);
System.out.println(“Thread:”+getName());
}
public void run()
{
try
{
for(int i=0;i<10;i++)
{
getCounterThread();
Thread.sleep(2000);
System.out.print(” “+getName()+” “+String.valueOf(i));
}
}
catch(InterruptedException ie)
{
ie.printStackTrace();
}
}
}
class ThreadDemo
{
public static void main(String args[])
{
MyThread t1 = new MyThread(“T1”);
MyThread t2 = new MyThread(“T2”);
t1.start();
t2.start();
}
}