-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMultithread1.java
105 lines (101 loc) · 3.44 KB
/
Multithread1.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import java.util.*;
class Even implements Runnable{
Queue <Integer>sharedListObject;
Even(Queue<Integer>sharedListObject){
this.sharedListObject=sharedListObject;
}
public void run(){
while(true){
synchronized(sharedListObject){
while(sharedListObject.size()<1 || sharedListObject.element()%2!=0){
try{
sharedListObject.wait();
}
catch(InterruptedException e){
e.printStackTrace();
}
}
int val = sharedListObject.remove();
System.out.println("square :"+val*val);
sharedListObject.notifyAll();
try{
Thread.sleep(1000);
}
catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
}
class Odd implements Runnable{
Queue <Integer>sharedListObject;
Odd(Queue<Integer>sharedListObject){
this.sharedListObject=sharedListObject;
}
public void run(){
while(true){
synchronized(sharedListObject){
while(sharedListObject.size()<1 || sharedListObject.element()%2==0){
try{
sharedListObject.wait();
}
catch(InterruptedException e){
e.printStackTrace();
}
}
int val = sharedListObject.remove();
System.out.println("Cube :"+val*val*val);
sharedListObject.notifyAll();
try{
Thread.sleep(1000);
}
catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
}
class Number implements Runnable{
Queue <Integer>sharedListObject;
Number(Queue<Integer>sharedListObject){
this.sharedListObject=sharedListObject;
}
public void run(){
while(true){
synchronized(sharedListObject){
while(sharedListObject.size()>=1){
try{
sharedListObject.wait();
}
catch(InterruptedException e){
e.printStackTrace();
}
}
Random r = new Random();
int randomNum = r.nextInt(1000);
System.out.println(Thread.currentThread().getName()+" "+"Random number : " + randomNum);
sharedListObject.add(randomNum);
sharedListObject.notifyAll();
try{
Thread.sleep(5000);
}
catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
}
public class Multithread1 {
public static void main(String[] args){
Queue <Integer> sharedListObject = new LinkedList<Integer>();
Thread random = new Thread(new Number(sharedListObject),"Random thread");
Thread even = new Thread(new Even(sharedListObject),"Odd thread");
Thread odd= new Thread(new Odd(sharedListObject),"Even thread");
random.start();
odd.start();
even.start();
}
}