//MultiThreading
class PrintTable
{
synchronized void print(int n) //synchronized method allows only 1 thread at a time
{
Thread ref = Thread.currentThread();
String name = ref.getName();
System.out.println(name);
// synchronized(this) //preferred way is to synchronize the block instead of complete method
{
if(n==2) //thread 0 with n=2 will be blocked and thread 1 will occupy lock
try{ wait(); } catch(Exception e){}
for (int i=1;i<=3;i++)
{
System.out.println(n*i);
try{ Thread.sleep(1000); } catch(Exception e){ }
}//for
notify(); //thread 1 will release the lock, thread 0 will access the shared resource
} //syn
} //print
} //class
//thread can be created by extending Thread class or runnable interface
class MyThread extends Thread
{ PrintTable p;
int n;
MyThread(PrintTable p, int n)
{
this.p = p;
this.n = n;
}
//override the run() exists in Runnable interface
public void run()
{
p.print(n);
}
}
class Test1{
public static void main(String args[])
{
PrintTable p = new PrintTable();
MyThread t1 = new MyThread(p,2);
MyThread t2 = new MyThread(p,3);
t1.start();
t2.start();
}
}
Output:
Thread-0
Thread-1
3
6
9
2
4
6