Skip to content

Instantly share code, notes, and snippets.

@wangzaixiang
Created September 17, 2012 13:29
Show Gist options
  • Save wangzaixiang/3737258 to your computer and use it in GitHub Desktop.
Save wangzaixiang/3737258 to your computer and use it in GitHub Desktop.
ThreadSwitch
package demo;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;
import java.nio.channels.Pipe.SinkChannel;
import java.nio.channels.Pipe.SourceChannel;
public class ThreadSwitch {
public static void main(String[] args) throws Exception {
Pipe pipeA = Pipe.open();
Pipe pipeB = Pipe.open();
new TaskA(pipeA.source(), pipeB.sink()).start();
int LOOP = 1000*1000;
Pipe.SinkChannel writer = pipeA.sink();
Pipe.SourceChannel reader = pipeB.source();
ByteBuffer buffer = ByteBuffer.allocate(1);
long begin = System.currentTimeMillis();
for(int i=0; i<LOOP; i++){
buffer.rewind();
buffer.put((byte)'H');
buffer.flip();
writer.write(buffer);
buffer.rewind();
reader.read(buffer);
}
long end = System.currentTimeMillis();
System.out.println("total time = " + (end-begin));
}
static class TaskA extends Thread {
private SourceChannel reader;
private SinkChannel writer;
TaskA(Pipe.SourceChannel reader, Pipe.SinkChannel writer) {
this.reader = reader;
this.writer = writer;
setDaemon(true);
}
@Override
public void run() {
ByteBuffer buffer = ByteBuffer.allocate(1);
try {
while (true) {
buffer.rewind();
reader.read(buffer);
buffer.flip();
writer.write(buffer);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment