Advertisement
// class A is implementing Runnable interface and its run() method
class A implements Runnable
{
synchronized public void run() //run() is synchronized, i.e. synchronized run of multiple threads,
{ // A thread executing run() is not replaced by another thread
for(int i=0;i<3;i++)
System.out.println(Thread.currentThread().getName());
}
public static void main(String... ar)
{
A ob= new A();
Thread t1= new Thread(ob,"ThreadA");
Thread t2= new Thread(ob,"ThreadB");
Thread t3= new Thread(ob,"ThreadC"); //Calling Thread's constructor & passing the object of
//A class that implemented Runnable interface &
//the name of new thread.
t1.start();
t2.start();
t3.start();
}
}
ThreadB
ThreadB
ThreadB
ThreadC
ThreadC
ThreadC
ThreadA
ThreadA
ThreadA
Advertisement
class A implements Runnable
{
synchronized public void run() //run method is marked synchronized, causing synchronized run of muliple threads
{
for(int i=0;i<3;i++)
{
try
{
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName());
}
catch(Exception e)
{
System.out.println(e);
}
}
}
public static void main(String... ar)
{
A ob= new A();
Thread t1= new Thread(ob,"ThreadA");
Thread t2= new Thread(ob,"ThreadB");
Thread t3= new Thread(ob,"ThreadC");
t1.start();
t2.start();
t3.start();
}
}
ThreadA
ThreadA
ThreadA
ThreadC
ThreadC
ThreadC
ThreadB
ThreadB
ThreadB
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement