交替打印素数
package test; import java.util.LinkedList; import java.util.List; /** * * @author jis * */ public class TestB { public static void main(String[] args) { BlockList<String> list = new BlockList<>(1); new Thread(new Printer(true, list)).start(); new Thread(new Printer(false, list)).start(); } } class Printer implements Runnable { BlockList<String> list; /** * 生产消费 打印质数 true 打印非质数 false */ boolean product = false; public Printer(boolean flag, BlockList<String> list) { this.product = flag; this.list = list; } @Override public void run() { String name = Thread.currentThread().getName(); Object obj = null; if (product) { for (int i = 0; i < 100; i++) { if (isPrime(i)) { list.offer("" + i); } else { System.err.println(name + "非素数" + ":" + i); } } } else { while (true) { obj = list.take(); System.err.println(name + "素数:" + obj); } } } /** * 判断是否是素数 * * @param a * @return */ public boolean isPrime(int a) { boolean flag = true; if (a < 2) {// 素数不小于2 return false; } else { for (int i = 2; i <= Math.sqrt(a); i++) { if (a % i == 0) {// 若能被整除,则说明不是素数,返回false flag = false; break;// 跳出循环 } } } return flag; } } class BlockList<T> { List<T> list = new LinkedList<>(); volatile int capicity; public BlockList(int capicity) { this.capicity = capicity; } public void offer(T data) { synchronized (list) { while (list.size() >= capicity) { try { list.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } list.add(data); list.notifyAll(); } } public T take() { T data = null; synchronized (list) { while (list.size() <= 0) { try { list.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } data = list.remove(0); list.notifyAll(); } return data; } }