java 并发相关博文

https://www.cnblogs.com/chengxiao/p/6528109.html  volatile关键字

 

http://www.importnew.com/16453.html  waite()和notify()实现生产者和消费者队列

 

/**
 * 生产者
 * @author ZXS
 *
 */
public class Product implements Runnable{
	
	private LinkedList<Integer> list;
	
	public Product(LinkedList<Integer> list) {
		this.list = list;
	}
	
	
	@Override
	public void run() {
		while (true) {
			synchronized (list) {
				while (list.size() == 100) {
					try {
						System.out.println("生产者" + Thread.currentThread().getId() +"生产已满");
						list.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				int i = new Random().nextInt();
				System.out.println("生产者" + Thread.currentThread().getId() +"生产了一个数字:" + i);
				list.add(i);
				list.notifyAll();
			}			
		}
	}

}
package thread;

import java.util.LinkedList;

/**
 * 消费者
 * @author ZXS
 * 
 */
public class Consumer implements Runnable{
	
	
	private LinkedList<Integer> list;
	
	public Consumer(LinkedList<Integer> list) {
		this.list = list;
	}
	
	
	@Override
	public void run() {
		while (true) 
		{
			synchronized (list) {
				while (list.isEmpty()) {
					try {
						System.out.println("生产者已经空!");
						list.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				System.out.println("Consumer消费者" + Thread.currentThread().getId() +" 消费了一个数字:" + list.remove() );
				list.notifyAll();
			}			
		}
	}

}
package thread;

import java.util.LinkedList;

/**
 * 线程间的通信 wait 和 notify 使用
 * @author ZXS
 *  
 */
public class ThreadTest1 
{	
	public static void main(String[] args) {
		LinkedList<Integer> list = new LinkedList<Integer>();
		Thread cousumer1 = new Thread(new Consumer(list));
		Thread product = new Thread(new Product(list));
		Thread cousumer2 = new Thread(new Consumer(list));
		product.start();
		cousumer1.start();
		cousumer2.start();
	}
}

 

http://www.importnew.com/19011.html   线程池源码分析

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值