线程基础(5)
线程基础(五)
SynchronizeTest
package org.wp.thread; public class SynchronizeTest { public static void main(String args[]) { SyncStack ss = new SyncStack(); new Thread(new Producer(ss)).start(); new Thread(new Consumer(ss)).start(); } } class Producer implements Runnable { private SyncStack ss; public Producer(SyncStack ss) { this.ss = ss; } @Override public void run() { for (int i = 0; i < 20; i++) { char c = (char) (Math.random() * 26 + 'A'); ss.push(c); try { Thread.sleep((int) (Math.random() * 100)); } catch (InterruptedException e) { e.printStackTrace(); } } } } class Consumer implements Runnable { private SyncStack ss; public Consumer(SyncStack ss) { this.ss = ss; } @Override public void run() { for (int i = 0; i < 20; i++) { ss.pop(); try { Thread.sleep((int) (Math.random() * 600)); } catch (InterruptedException e) { e.printStackTrace(); } } } } class SyncStack { private int index = 0; private char[] data = new char[6]; public synchronized void push(char c) { while (index == data.length) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.notify(); data[index] = c; index++; System.out.println("生产了:" + c); } public synchronized void pop() { while (index == 0) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.notify(); index--; System.out.println("消费了:" + data[index]); } }
PipedStreamTest
package org.wp.thread; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; /** * connect(PipedOutputStream src) * 使此管道输入流连接到管道输出流 src * 如果此对象已经连接到其他某个管道输出流,则抛出IOException * * @author wp * */ public class PipedStreamTest { public static void main(String args[]) { PipedOutputStream pos = new PipedOutputStream(); PipedInputStream pis = new PipedInputStream(); try { pis.connect(pos); } catch (IOException e) { e.printStackTrace(); } new Sender(pos).start(); new Receiver(pis).start(); } } class Sender extends Thread { private DataOutputStream dos; public Sender(PipedOutputStream pos) { dos = new DataOutputStream(pos); } @Override public void run() { try { dos.writeUTF("你好!"); dos.close(); } catch (IOException e) { e.printStackTrace(); } } } class Receiver extends Thread { private DataInputStream dis; public Receiver(PipedInputStream pis) { dis = new DataInputStream(pis); } @Override public void run() { try { System.out.println(dis.readUTF()); dis.close(); } catch (IOException e) { e.printStackTrace(); } } }