Source Code:
import java.util.*;
class star //class containing synchronized methods
{
int ch=0;
synchronized void printstar()
{
try{
if(ch==1)//star was printed last
{
wait();
}
System.out.print("*");
ch=1;
notify();
}catch(InterruptedException e){System.out.println("error");
}
}
synchronized void printslash()
{
try{ if(ch==0)//slash was printed previously
{
wait();
}
System.out.print("/");
ch=0;//slash printed
notify();
}catch(InterruptedException e){};
}
}
class printx extends Thread //for printing star
{
star r,s;
printx(star r)
{
this.r=r;
}
public void run()
{
int f=0;
while(f!=10)
{
r.printstar();
f++;
}
}
}
class print extends Thread///for printing slash
{
star r,s;
print(star r)
{
this.r=r;
}
public void run()
{
int f=0;
while(f!=15)
{
r.printslash();
f++;
}
}
}
class Demo
{
public static void main(String args[])
{
star q=new star();
print p=new print(q);
printx px=new printx(q);
p.start();//thread 1 starts
px.start();//thread 2 starts
}
}
import java.util.*;
class star //class containing synchronized methods
{
int ch=0;
synchronized void printstar()
{
try{
if(ch==1)//star was printed last
{
wait();
}
System.out.print("*");
ch=1;
notify();
}catch(InterruptedException e){System.out.println("error");
}
}
synchronized void printslash()
{
try{ if(ch==0)//slash was printed previously
{
wait();
}
System.out.print("/");
ch=0;//slash printed
notify();
}catch(InterruptedException e){};
}
}
class printx extends Thread //for printing star
{
star r,s;
printx(star r)
{
this.r=r;
}
public void run()
{
int f=0;
while(f!=10)
{
r.printstar();
f++;
}
}
}
class print extends Thread///for printing slash
{
star r,s;
print(star r)
{
this.r=r;
}
public void run()
{
int f=0;
while(f!=15)
{
r.printslash();
f++;
}
}
}
class Demo
{
public static void main(String args[])
{
star q=new star();
print p=new print(q);
printx px=new printx(q);
p.start();//thread 1 starts
px.start();//thread 2 starts
}
}
output:*/*/*/*/*/*/*/*/
explanation:we use synchronization here by using wait() and notify() method .
when a star is printed we make ch=1.
when a slsh is printed we make ch=0.
explanation:we use synchronization here by using wait() and notify() method .
when a star is printed we make ch=1.
when a slsh is printed we make ch=0.
No comments:
Post a Comment