-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPipeTest.java
More file actions
87 lines (69 loc) · 2.41 KB
/
PipeTest.java
File metadata and controls
87 lines (69 loc) · 2.41 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package com.example.nio.pipe;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
/**
* Created by guolei on 16-8-7.
* ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
* | 没有神兽,风骚依旧! |
* | QQ:1120832563 |
* ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
*/
/**
* 可以在线程之间传递数据
*/
public class PipeTest {
public static void main(String[] args){
Pipe pipe;
Pipe.SinkChannel sinkChannel;
Pipe.SourceChannel sourceChannel;
try {
pipe = Pipe.open();
new Thread(new ReadWork(pipe.source())).start();
new Thread(new WriteWork(pipe.sink())).start();
} catch (IOException e) {
e.printStackTrace();
}
}
public static class WriteWork implements Runnable{
public Pipe.SinkChannel sinkChannel;
public WriteWork(Pipe.SinkChannel sinkChannel){
this.sinkChannel = sinkChannel;
}
@Override
public void run() {
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
try {
byteBuffer.put(new String("输入的数据").getBytes("utf-8"));
byteBuffer.flip();
sinkChannel.write(byteBuffer);
byteBuffer.clear();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static class ReadWork implements Runnable{
public Pipe.SourceChannel sourceChannel;
public ReadWork(Pipe.SourceChannel sourceChannel){
this.sourceChannel = sourceChannel;
}
@Override
public void run() {
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while (true){
try {
while (sourceChannel.read(byteBuffer) != -1){
System.err.println("读取到的数据 "+ new String(byteBuffer.array()).trim());
return;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}