-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththread.java
90 lines (90 loc) · 2.56 KB
/
thread.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
class Shareddata
{
public static int randomint;
public static boolean isgen=false;
public static final Shareddata lock = new Shareddata();
}
class random extends Thread
{
public void run(){
for(int i=0;i<5;i++){
synchronized(Shareddata.lock)
{
Shareddata.randomint=(int)(Math.random()*100);
System.out.println("num Gen"+Shareddata.randomint);
Shareddata.isgen=true;
Shareddata.lock.notifyAll();
try{
Thread.sleep(1000);
Shareddata.lock.wait();
}
catch(InterruptedException e){
System.out.println(e);
}
}
}
}
}
class square extends Thread{
public void run(){
for(int i=0;i<5;i++){
synchronized(Shareddata.lock){
while(!Shareddata.isgen){
try{
Shareddata.lock.wait();
}
catch(InterruptedException e1)
{
System.out.println(e1);
}
}
if(Shareddata.randomint%2==0){
System.out.println("square is"+Shareddata.randomint*Shareddata.randomint);
Shareddata.isgen=false;
Shareddata.lock.notifyAll();
}
}
}
}
}
class cube extends Thread{
public void run(){
for(int i=0;i<5;i++){
synchronized(Shareddata.lock){
while(!Shareddata.isgen){
try{
Shareddata.lock.wait();
}
catch(InterruptedException e2)
{
System.out.println(e2);
}
}
if(Shareddata.randomint%2!=0){
System.out.println("cube is"+Shareddata.randomint*Shareddata.randomint*Shareddata.randomint);
Shareddata.isgen=false;
Shareddata.lock.notifyAll();
}
}
}
}
}
public class Main3{
public static void main (String [] args){
random r = new random();
square s = new square();
cube c = new cube();
r.start();
s.start();
c.start();
try{
r.join();
s.join();
c.join();
}
catch(InterruptedException e3)
{
System.out.println(e3);
}
}
}