创建thread1类继承thread
package com.ysj.control;
import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;
public class Thread1 {
// 定义一个阻塞队列用来存储生产出来的商品
private LinkedBlockingQueue<Integer> link = new LinkedBlockingQueue<Integer>();
// 定义生产商品个数
private static final int size = 10;
// 定义启动线程的标志,为0时,启动生产商品的线程;为1时,启动消费商品的线程
private int flag = 0;
public class Linklock extends Thread {
@Override
public void run() {
int new_flag =flag++;
System.out.println("启动线程" + new_flag);
if (new_flag == 0) {
for (int i = 0; i < size; i++) {
int b=new Random().nextInt(255);
System.out.println("生产商品"+b+"号");
try{
link.put(b);
System.out.println("剩下商品还有"+link.size()+"个");
}catch(Exception e){
e.printStackTrace();
}
}
}else{
for(int i=0;i<size/2;i++){
try {
int n=link.take();
System.out.println("消费者买走了"+n+"号");
System.out.println("还剩下商品"+link.size()+"个");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
利用main函数启动线程
package com.ysj.control;
import com.ysj.control.Thread1.Linklock;
/**
* 用阻塞队列实现线程同步 LinkedBlockingQueue的使用
*
* @author XIEHEJUN
*
*/
public class test {
public static void main(String[] args) {
Thread1 t= new Thread1();
Linklock lk = t.new Linklock();
Thread thread1 = new Thread(lk);
Thread thread2 = new Thread(lk);
thread1.start();
thread2.start();
}
}
linkedBlockingQueue简介 链接 http://blog.csdn.net/dachengxi/article/details/52133024