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

class PrintNumber Wait Notify

The document contains two Java classes, PrintNumber and MyThread, which demonstrate the use of synchronization in multithreading. The first implementation synchronizes the print method to ensure thread safety, while the second implementation introduces wait and notify mechanisms to control thread execution based on the input number. Both implementations create instances of MyThread to print multiples of given numbers concurrently.

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)
2 views2 pages

class PrintNumber Wait Notify

The document contains two Java classes, PrintNumber and MyThread, which demonstrate the use of synchronization in multithreading. The first implementation synchronizes the print method to ensure thread safety, while the second implementation introduces wait and notify mechanisms to control thread execution based on the input number. Both implementations create instances of MyThread to print multiples of given numbers concurrently.

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

class PrintNumber

{
synchronized void print(int n)
{
Thread t = Thread.currentThread();
String name = t.getName();
System.out.println(name);
for(int i = 1; i<=3 ; i++)
{
System.out.println(n*i);
try{Thread.sleep(400);} catch(Exception E){}
}
}
}

class MyThread extends Thread


{
private PrintNumber p;
private int n;
MyThread(PrintNumber p, int n){
this.p = p;
this.n = n;
}
public void run()
{
p.print(n);
}
}

class Test
{
public static void main(String args[])
{
PrintNumber p = new PrintNumber();
MyThread t1 = new MyThread(p,2);
MyThread t2 = new MyThread(p,3);
t1.start();
t2.start();
}
}

class PrintNumber
{
void print(int n)
{
Thread t = Thread.currentThread();
String name = t.getName();
System.out.println(name);
synchronized(this){
if(n==2)
try{wait();} catch(Exception E){};

for(int i = 1; i<=3 ; i++)


{
System.out.println(n*i);
try{Thread.sleep(400);} catch(Exception E){}
} //for
notify();
} //block
} //print()
} // class

class MyThread extends Thread


{
private PrintNumber p;
private int n;
MyThread(PrintNumber p, int n){
this.p = p;
this.n = n;
}
public void run()
{
p.print(n);
}
}

class TestWait
{
public static void main(String args[])
{
PrintNumber p = new PrintNumber();
MyThread t1 = new MyThread(p,2);
MyThread t2 = new MyThread(p,3);
t1.start();
t2.start();
}
}

You might also like