本文共 2970 字,大约阅读时间需要 9 分钟。
public class Message { private String content; public Message(String content) { this.content=content; } public void display(){ System.out.println(content); } }
public class PollingThread extends Thread implements Runnable { public static Queuequeue = new LinkedTransferQueue (); @Override public void run() { while (true) { while (!queue.isEmpty()) { queue.poll().display(); } } } }
public class Main { public static void main(String[] args){ PollingThread pollingThread=new PollingThread(); pollingThread.start(); int i=1; while(true) { PollingThread.queue.offer(new Message("新消息"+i)); i++; try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } } }
新消息1新消息2新消息3新消息4新消息5 新消息6 新消息7 新消息8 新消息9 新消息10 新消息11 新消息12 新消息13 新消息14 新消息15 ......
public class PollingThread extends Thread implements Runnable { public static Queuequeue = new LinkedTransferQueue (); @Override public void run() { while (true) { while (!queue.isEmpty()) { queue.poll().display(); } //把队列中的消息全部打印完之后让线程阻塞 synchronized (Lock.class) { try { Lock.class.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
public class Main { public static void main(String[] args){ PollingThread pollingThread=new PollingThread(); pollingThread.start(); int i=1; while(true) { PollingThread.queue.offer(new Message("新消息"+i)); i++; //有消息入队后激活轮询线程 synchronized (Lock.class) { Lock.class.notify(); } try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } } }
新消息1新消息2新消息3新消息4新消息5 新消息6 新消息7 新消息8 新消息9 新消息10 新消息11 ......
http://blog.csdn.net/q15858187033/article/details/60583631