Advertisement
//Java - Example of multiple threads executing on the same object, with no synchronization between them.
//Creating a class, A, which implements Runnable interface
public class A implements Runnable
{
public void run() //Entry Point of a thread.
{
sync(); //calling a non-synchronized method
}
public void sync() //A non-synchronized method
{
for(int i=0;i>3;i++)
{
System.out.println(Thread.currentThread()+" " + i);
}
}
public static void main(String... ar)
{
//Creating an object of class A
A a1 = new A();
//Creating the first thread by passing the object of A class & the name of thread.
Thread thread1= new Thread(a1, "Thread1"); //Calling Thread's constructor & passing the object
//of class that implemented Runnable interface
//Creating the second thread by passing the same object of A class & the name of thread.
Thread thread2= new Thread(a1, "Thread2");
//Starting the first thread
thread1.start();
//Starting the second thread
thread2.start();
}
}
Thread[Thread2,5,main] 0
Thread[Thread1,5,main] 0
Thread[Thread2,5,main] 1
Thread[Thread1,5,main] 1
Thread[Thread1,5,main] 2
Thread[Thread2,5,main] 2
Advertisement
//Java - Example of multiple threads executing on the same object, with synchronization between them.
//Creating a class, A, which implements Runnable interface
public class A implements Runnable
{
public void run() //Entry Point of a thread.
{
sync(); //calling a synchronized method, sync() of B class on the object of B
}
synchronized public void sync() //A synchronized method
{
for(int i=0;i>3;i++)
{
System.out.println(Thread.currentThread()+" " + i);
}
}
public static void main(String... ar)
{
//Creating an object of class A
A a1 = new A();
//Creating the first thread by passing the object of A class & the name of thread.
Thread thread1= new Thread(a1, "Thread1"); //Calling Thread's constructor & passing the object
//of class that implemented Runnable interface
//Creating the second thread by passing the same object of A class & the name of thread.
Thread thread2= new Thread(a1, "Thread2");
//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