java多线程 BlockingQueue 和 SynchronousQueues

参考:http://www.ibm.com/developerworks/cn/java/j-5things4.html

【关于 java.util.concurrent 您不知道的 5 件事,第 1 部分】

1,BlockingQueue

public class ABQApp {
	public static void main(String[] args) {
		BlockingQueue<String> drop = new ArrayBlockingQueue<String>(1, true);
		new Thread(new Producer(drop)).start();
		new Thread(new Consumer(drop)).start();
	}
}

class Producer  implements Runnable {
	private BlockingQueue<String> drop;
	List<String> messages = Arrays.asList(
			"Mares eat oats",
			"Does eat oats",
			"Little lambs eat ivy",
	"Wouldn't you eat ivy too?");

	public Producer(BlockingQueue<String> d) { this.drop = d; }

	public void run() {
		try {
			for (String s : messages)
				drop.put(s);
			drop.put("DONE");
		} catch (InterruptedException intEx) {
			System.out.println("Interrupted! " + 
			"Last one out, turn out the lights!");
		}
	}    
}

class Consumer implements Runnable {
	private BlockingQueue<String> drop;
	public Consumer(BlockingQueue<String> d) { this.drop = d; }

	public void run() {
		try {
			String msg = null;
			while (!((msg = drop.take()).equals("DONE")))
				System.out.println(msg);
		} catch (InterruptedException intEx) {
			System.out.println("Interrupted! " + 
			"Last one out, turn out the lights!");
		}
	}
}

 

2,SynchronousQueues

 

public class SynQApp {
	public static void main(String[] args) {
		BlockingQueue<String> drop = new SynchronousQueue<String>();
		(new Thread(new Producer(drop))).start();
		(new Thread(new Consumer(drop))).start();
	}
}
class Producer implements Runnable {
	private BlockingQueue<String> drop;
	List<String> messages = Arrays.asList(
			"Mares eat oats",
			"Does eat oats",
			"Little lambs eat ivy",
	"Wouldn't you eat ivy too?");
	public Producer(BlockingQueue<String> d) { this.drop = d; }
	public void run() {
		try	{
			for (String s : messages)
				drop.put(s);
			drop.put("DONE");
		} catch (InterruptedException intEx)	{
			System.out.println("Interrupted! " + 
			"Last one out, turn out the lights!");
		}
	}    
}

class Consumer implements Runnable {
	private BlockingQueue<String> drop;
	public Consumer(BlockingQueue<String> d) { this.drop = d; }
	public void run()	{
		try	{
			String msg = null;
			while (!((msg = drop.take()).equals("DONE")))
				System.out.println(msg);
		} catch (InterruptedException intEx)	{
			System.out.println("Interrupted! " + 
			"Last one out, turn out the lights!");
		}
	}
}

 

总的来说SynchronousQueue,就保证了放一个读一个,线程同步了,然后ArrayBlockingQueue<String>(1, true);就和SynchronousQueue一样了。

你可能感兴趣的:(java,多线程,thread,IBM,J#)