多个线程各自占有一些共享资源,两个或以上线程都在等待对方释放资源,都停止执行
产生死锁的四个必要条件:
JUC包下的显示定义同步锁,更强大的线程同步机制
ReentrantLock类synchronized形同的并发性和内存语义
private final ReentrantLock lock = new ReentrantLock();
lock.lock();
lock.unlock();
生产者消费者模式
Java提供了几个方法解决线程之间的通信问题
方法名 | 作用 |
---|---|
wait() | 表示线程一直等待直到其他线程通知,与sleep不同,会释放锁 |
wait(long timeout) | 指定等待的毫秒数 |
notify() | 唤醒一个处于等待状态的线程 |
notifyAll() | 唤醒同一个对象上所有调用wait()方法的线程,优先级高优先调 |
都只能在同步方法或者同步代码块中使用,否则会抛出异常
//管程法:利用缓冲区
public class TestPC{
public static void mian(String[] args){
SynContainer container = new SynContainer();
new Producer(container).start();
new Consumer(container).start();
}
}
//生产者
class Producer extends Thread{
SynContainer container;
public Producer(SynContainer container){
this.container = container;
}
//生产
public void run(){
for(int i=0; i<100; i++){
container.push(new Chicken[i]);
System.out.println("生产了"+i+"只鸡");
}
}
}
//消费者
class Consumer extends Thread{
SynContainer container;
public Consumer(SynContainer container){
this.container = container;
}
//消费
public void run(){
for(int i=0 ;i<100;i++){
System.out.println("消费了"+container.pop().id+"只鸡");
}
}
}
//产品
class Chicken{
int id;
public Chicken(int id){
this.id = id;
}
}
//缓冲区
class SynContainer{
//需要一个容器大小
chickens[] chicken = new Chicken[10];
//容器计数器
int count = 0;
//生产者放入产品
public synchronized void push(Chicken chicken){
//如果容器满了,就需要等待消费者消费
if(count == chicken.length){
//通知消费者消费,生产等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果没有满,需要丢入产品
chickens[count] = chicken;
count++;
//通知消费者消费
this.notifyAll();
}
//消费者消费产品
public synchronuzed Chicken pop(){
//判断能否消费
if(count == 0){
//通知生产者生产,消费者等待
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//如果可以消费
count--;
Chicken chicken = chickens[count];
//通知生产者生产
this.notifyAll();
return chicken;
}
}
Executors:工具类、线程池的工厂类,用于创建并返回不同类型的线程池
public class TestPool{
public static void main(String[] args){
//创建服务,创建线程池
//newFixedThreadPool参数:线程池大小
ExecutorService service = Executors.newFixedThreadPool(10);
//执行
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
//2.关闭连接
service.shutdown();
}
}
class MyThread implements Runnable{
public void run(){
System.out.println(Thread.currentThread().getName());
}
}
原文:https://www.cnblogs.com/GladysJiu/p/14411402.html