Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class SynchronizedInputStream extends InputStream {
- private static volatile boolean running = true;
- private static final BlockingQueue<Integer> readQueue = new LinkedBlockingQueue<>();
- private static final Thread [] catchers = new Thread[256];
- private static final SynchronizedInputStream INSTANCE = new SynchronizedInputStream();
- public static SynchronizedInputStream get() {
- return INSTANCE;
- }
- private SynchronizedInputStream() {
- for (int i = -128; i < 128; i++ ) {
- catchers[ i + 128 ] = new Thread( new ByteCatcher( i ) );
- catchers[ i + 128 ].start();
- }
- }
- @Override
- public int read() throws IOException {
- if (!running && readQueue.isEmpty()) {
- return -1;
- }
- try {
- return readQueue.take();
- } catch (InterruptedException e) {
- throw new IOException( "Read queue interrupted.", e );
- }
- }
- @Override
- public void close() throws IOException {
- running = false;
- for (Thread t : catchers) {
- t.interrupt();
- }
- }
- private static class ByteCatcher implements Runnable {
- private final Integer value;
- private ByteCatcher( int i ) {
- this.value = i;
- }
- @Override
- public void run() {
- while (running) {
- synchronized (value) {
- try {
- value.wait();
- Integer unsigned = value + 128; // we're doing another unbox/box conversion here but what the hell
- readQueue.add( unsigned );
- } catch (InterruptedException e) {
- return;
- }
- }
- }
- }
- }
- }
- public class SynchronizedOutputStream extends OutputStream {
- private static final int TRANSMISSION_DELAY = 1;
- private static final SynchronizedOutputStream INSTANCE = new SynchronizedOutputStream();
- public static final SynchronizedOutputStream get() {
- return INSTANCE;
- }
- @Override
- public void write(int arg) throws IOException {
- Integer value = arg - 128;
- try {
- Thread.sleep( TRANSMISSION_DELAY );
- } catch (InterruptedException e) {
- }
- synchronized (value) {
- value.notifyAll();
- }
- }
- @Override
- public void close() throws IOException {
- SynchronizedInputStream.get().close();
- }
- }
- public class Main {
- public static void main(String[] args) throws IOException, InterruptedException {
- new Thread() {
- public void run() {
- final SynchronizedInputStream sis = SynchronizedInputStream.get();
- InputStreamReader isr = new InputStreamReader( sis );
- BufferedReader br = new BufferedReader( isr );
- try {
- System.out.println( br.readLine() );
- } catch (IOException e) {
- e.printStackTrace();
- }
- };
- }.start();
- Thread.sleep( 1000 );
- SynchronizedOutputStream sos = SynchronizedOutputStream.get();
- PrintWriter pw = new PrintWriter( sos, true );
- pw.println( "Hello world!");
- pw.flush();
- pw.close();
- }
- }
Add Comment
Please, Sign In to add comment