Java-线程通信

本文详细介绍了Java中的线程通信,包括死锁的产生原因与解决策略,以及wait(), notify(), notifyAll()的使用方法。通过生产者与消费者经典案例展示了线程间的协调合作,并简单提及了线程池的概念及其优势。
摘要由CSDN通过智能技术生成

Java-线程通信

1 死锁

1.1 产生原因

​ 不同的线程分别占用对方需要的同步资源不放弃,都在等待对方放弃
自己需要的同步资源,就形成了线程的死锁

注意:

​ 出现死锁后,不会出现异常,不会出现提示,只是所有的线程都处于 阻塞状态,无法继续

1.2 解决方法

  1. 专门的算法、原则
  2. 尽量减少同步资源的定义
  3. 尽量避免嵌套同步

2 线程通信

2.1 线程挂起与唤醒

wait() 与 notify() 和 notifyAll()
a) wait():令当前线程挂起并放弃CPU、同步资源并等待,使别的线程可访问并修改共享资源,而当 前线程排队等候其他线程调用notify()或notifyAll()方法唤醒,唤醒后等待重新获得对监视器的所有 权后才能继续执行。
b) notify():唤醒正在排队等待同步资源的线程中优先级最高者结束等待
c) notifyAll ():唤醒正在排队等待资源的所有线程结束等待.

注意:

​ 这三个方法只有在synchronized方法或synchronized代码块中才能使用,否则会报java.lang.IllegalMonitorStateException异常

​ 因为这三个方法必须有锁对象调用,而任意对象都可以作为synchronized的同步锁,因此这三个方法只能在Object类中声明

2.2 wait()

  1. 在当前线程中调用方法: 对象名.wait()
  2. 使当前线程进入等待(某对象)状态 ,直到另一线程对该对象发出 notify
    (或notifyAll) 为止。
  3. 调用方法的必要条件:当前线程必须具有对该对象的监控权(加锁)
  4. 调用此方法后,当前线程将释放对象监控权 ,然后进入等待
  5. 在当前线程被notify后,要重新获得监控权,然后从断点处继续代码的执行

2.3 notify和notifyAll

  1. 在当前线程中调用方法: 对象名.notify()
  2. 功能:唤醒等待该对象监控权的一个/所有线程。
  3. 调用方法的必要条件:当前线程必须具有对该对象的监控权(加锁)

2.4 经典案例之生产者与消费者

​ 生产者(Productor)将产品交给店员(Clerk),而消费者(Customer)从店员处 取走产品,店员一次只能持有固定数量的产品(比如:20),如果生产者试图 生产更多的产品,店员会叫生产者停一下,如果店中有空位放产品了再通 知生产者继续生产;如果店中没有产品了,店员会告诉消费者等一下,如 果店中有产品了再通知消费者来取走产品。
​ 这里可能出现两个问题:
​ 生产者比消费者快时,消费者会漏掉一些数据没有取到。
​ 消费者比生产者快时,消费者会取相同的数据。

package _homework_210702;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 1生产者和消费者的多线程案例 2 角色划分:生产者,资源池,消费者 3 以超市售卖商品为例
 * 
 * @author codelx
 * @date 2021年7月2日
 */

public class ProducerAndCustomer {

	public static void main(String[] args) {
		// 初始化角色
		ShopPool shopPool = new ShopPool();
		ProducerRunnable producerRunnable = new ProducerRunnable(shopPool);
		CustomerRunnable customerRunnable = new CustomerRunnable(shopPool);
		// 循环构建线程并启动
		List<Thread> producerThreadList = new ArrayList<Thread>();
		List<Thread> customerThreadList = new ArrayList<Thread>();
		for (int i = 1; i <= 3; i++) {
			Thread thread1 = new Thread(producerRunnable, "生产者-" + i);
			producerThreadList.add(thread1);
			thread1.start();
		}
		for (int i = 1; i <= 5; i++) {
			Thread thread2 = new Thread(customerRunnable, "消费者-" + i);
			customerThreadList.add(thread2);
			thread2.start();
		}
		while (true) {
			if (shopPool.isAllOver()) {
				// 真正去打断生产和消费线程,防止资源浪费

				for (Thread t : producerThreadList) {
					t.stop();
				}

				for (Thread t : customerThreadList) {
					t.stop();
				}
				System.out.println("商品卖完了");
				break;
			}
			System.out.println("店铺营业中");
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		System.out.println("关门了");
	}
}

/**
 * 定义生产者类,实现相关功能
 * 
 * @author codelx
 * @date 2021年7月2日
 */

class ProducerRunnable implements Runnable {
	private ShopPool shopPool;
	private int IdCounter = 1;

	public ProducerRunnable(ShopPool shopPool) {
		this.shopPool = shopPool;
	}

	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName() + "上岗了");
		for (int i = 1; i <= 5; i++) {
			synchronized (shopPool) {
				Shop shop = new Shop(IdCounter, "百事可乐", 3.5, "饮料");
				IdCounter++;
				if (shopPool.ShopSize() >= 6) {
					try {
						System.out.println(Thread.currentThread().getName()
								+ "由于商品太多休息了");
						shopPool.wait();
						System.out.println(Thread.currentThread().getName()
								+ "又接着开始生产商品了");
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				shopPool.notifyAll();
				shopPool.ShopAdd(shop);
				System.out.println(Thread.currentThread().getName() + "生产了商品"
						+ shop);
			}
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

/**
 * 定义消费者类,实现相关功能
 * 
 * @author codelx
 * @date 2021年7月2日
 */
class CustomerRunnable implements Runnable {
	private ShopPool shopPool;
	private int IdCounter = 1;

	public CustomerRunnable(ShopPool shopPool) {
		this.shopPool = shopPool;
	}

	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName() + "来到店里");
		for (int i = 1; i <= 5; i++) {
			synchronized (shopPool) {
				Shop shop = null;
				while ((shop = shopPool.ShopReduce()) == null) {
					try {
						System.out.println(Thread.currentThread().getName()
								+ "由于没货了,等待补货");
						shopPool.wait();
						System.out.println(Thread.currentThread().getName()
								+ "又接着购买百事可乐了");
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				shopPool.notifyAll();
				System.out.println(Thread.currentThread().getName() + "购买了商品"
						+ shop);
			}
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

/**
 * 定义商品资源池
 * 
 * @author codelx
 * @date 2021年7月2日
 */
class ShopPool {
	// 设置生产阀值和消费阀值
	public int maxProducerNumber = 15;
	public int maxConsumerNumber = 15;
	public int currentProducerNumber = 0;
	public int currentConsumerNumber = 0;

	// 创建资源池列表
	LinkedList<Shop> shopList = new LinkedList<Shop>();

	// 创建生产商品的方法
	public void ShopAdd(Shop shop) {
		shopList.add(shop);
		currentProducerNumber++;
	}

	// 创建消费者消费的方法
	public Shop ShopReduce() {
		Shop shop = shopList.poll();
		if (shop != null) {
			currentConsumerNumber++;
		}
		return shop;
	}

	// 判断资源池的大小
	public int ShopSize() {
		return shopList.size();
	}

	// 判定是否终止消费者和生产者的所有线程,即工作线程
	public boolean isAllOver() {
		return this.currentConsumerNumber >= this.maxProducerNumber;
	}
}

/**
 * 定义商品类,描述商品的属性
 * 
 * @author codelx
 * @date 2021年7月2日
 */
class Shop {
	// 商品编号
	private int Id;
	// 商品名字
	private String Name;
	// 商品价格
	private double Price;
	// 商品类型
	private String Type;

	@Override
	public String toString() {
		return "Shop [Id=" + Id + ", Name=" + Name + ", Price=" + Price
				+ ", Type=" + Type + "]";
	}

	public Shop(int id, String name, double price, String type) {
		super();
		Id = id;
		Name = name;
		Price = price;
		Type = type;
	}

	public int getId() {
		return Id;
	}

	public void setId(int id) {
		Id = id;
	}

	public String getName() {
		return Name;
	}

	public void setName(String name) {
		Name = name;
	}

	public double getPrice() {
		return Price;
	}

	public void setPrice(double price) {
		Price = price;
	}

	public String getType() {
		return Type;
	}

	public void setType(String type) {
		Type = type;
	}

}

3 线程池(仅作了解)

背景:

经常创建和销毁、使用量特别大的资源,比如并发情况下的线程, 对性能影响很大。

思路:

提前创建好多个线程,放入线程池中,使用时直接获取,使用完 放回池中。可以避免频繁创建销毁、实现重复利用。类似生活中的公共交 通工具。

好处:
a) 提高响应速度(减少了创建新线程的时间)
b) 降低资源消耗(重复利用线程池中线程,不需要每次都创建)
c) 便于线程管理
i. corePoolSize:核心池的大小
ii. maximumPoolSize:最大线程数
iii. keepAliveTime:线程没有任务时最多保持多长时间后会终止

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值