-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHoseePipe.java
More file actions
70 lines (62 loc) · 1.84 KB
/
HoseePipe.java
File metadata and controls
70 lines (62 loc) · 1.84 KB
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
package Thread;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class HoseePipe {
final PipedInputStream pis = new PipedInputStream();
final PipedOutputStream pos = new PipedOutputStream();
{
try {
pis.connect(pos);
} catch (IOException e) {
e.printStackTrace();
}
}
class Producer implements Runnable {
@Override
public void run() {
try {
while (true) {
int b = (int) (Math.random() * 255);
System.out.println("Producer: a byte, the value is " + b);
pos.write(b);
pos.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
pos.close();
pis.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
}
class Consumer implements Runnable {
@Override
public void run() {
try {
while (true) {
int b = pis.read();
System.out.println("Consumer: a byte, the value is " + String.valueOf(b));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
pos.close();
pis.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
}
public static void main(String[] args) throws Exception {
HoseePipe hosee = new HoseePipe();
new Thread(hosee.new Producer()).start();
new Thread(hosee.new Consumer()).start();
}
}