2 第十四天:高级:线程锁+ThreadLocal

2.1 生产者和消费者模型

线程间通信模型

  • 生产者产生数据,放入一个数据容器
  • 消费者从容器来获取数据
  • 线程间解耦

Producer 类

package cn.edut.com.tarena.thread;

import java.util.Queue;
import java.util.Random;

public class Producer extends Thread {
	Queue<Character> queue;

	public Producer(Queue<Character> queue) {
		this.queue = queue;
	}

	@Override
	public void run() {
		while (true) {
			synchronized (queue) {
				char c = (char) ('a' + new Random().nextInt(26));
				queue.offer(c);
				System.out.println("size:"+queue.size()+" <<< " + c);
			}
		}
	}
}

Customer 类

package cn.edut.com.tarena.thread;

import java.util.Queue;

public class Customer  extends Thread{
	Queue<Character> queue; 
	public Customer(Queue<Character> queue) {
		this.queue = queue; 
	}
	@Override
	public void run() {
		while (true) {
			synchronized (queue) {
				char c = queue.poll() ;
				System.out.println("size:"+queue.size()+" >>>>>> "+c);
			}
		}
	}
}

测试类

package cn.edut.com.tarena.thread;

import java.util.Queue;
import java.util.Random;

public class Producer extends Thread {
	Queue<Character> queue;

	public Producer(Queue<Character> queue) {
		this.queue = queue;
	}

	@Override
	public void run() {
		while (true) {
			synchronized (queue) {
				char c = (char) ('a' + new Random().nextInt(26));
				queue.offer(c);
				System.out.println("size:"+queue.size()+" <<< " + c);
			}
		}
	}
}

只有进没有出,为什么?
往下看



2.2 等待和通知