0% found this document useful (0 votes)
8 views2 pages

Thread

The document presents a Java program demonstrating multithreading using a synchronized method to print multiplication tables. It defines a PrintTable class with a synchronized print method that allows only one thread to execute at a time, while two MyThread instances are created to run concurrently. The output shows the order of thread execution and the multiplication results for the numbers 2 and 3.

Uploaded by

Thunder
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views2 pages

Thread

The document presents a Java program demonstrating multithreading using a synchronized method to print multiplication tables. It defines a PrintTable class with a synchronized print method that allows only one thread to execute at a time, while two MyThread instances are created to run concurrently. The output shows the order of thread execution and the multiplication results for the numbers 2 and 3.

Uploaded by

Thunder
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

//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

You might also like