1.先是实现一个Producer类来继承Runnable。
实例变量是List类,重写Runnable方法:run方法下一直不断地进行生产,同时给对象加锁,当仓库中的元素大于1时,前线程进入等待状态,并且释放之前占有的List集合的锁。
class Producer implements Runnable{
private List list;
public List getList() {
return list;
}
public void setList(List list) {
this.list = list;
}
public Producer(List list) {
this.list = list;
}
@Override
public void run() {
while(true){
synchronized (list){
if(list.size() > 0){
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Object obj = new Object();
list.add(obj);
System.out.println(Thread.currentThread().getName() + "--->>>" + obj);
list.notify();
}
}
}
}
2.在实现一个Consumer类实现Runnable接口。和Producer的实现变量一样,只是在重写run方法时稍有改变。判断的条件变成了仓库里面是否有元素。
class Consumer implements Runnable{
private List list;
public Consumer(List list){
this.list = list;
}
@Override
public void run() {
while(true){
synchronized (list){
if(list.size() == 0){
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Object obj = list.remove(0);
System.out.println(Thread.currentThread().getName()+ "--->>>" +obj);
list.notify();
}
}
}
}
3.在实现主程序。先创建一个List集合,在创建两个线程,将创建的集合放到线程中去。
public class ThreadTest02 {
public static void main(String[] args) {
List list = new ArrayList();
Thread t1 = new Thread(new Producer(list));
Thread t2 = new Thread(new Consumer(list));
t1.setName("生产者线程");
t2.setName("消费者线程");
t1.start();
t2.start();
}
}