多线程之死锁、生产者与消费者模型以及线程池

死锁产生的四个必要条件
  • 互斥条件:一个资源每次只能被一个进程使用
  • 请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放
  • 不剥夺条件:进程已获得的资源,在未使用完之前,不能强制剥夺
  • 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系
实例
package com.yeyue.thread;

public class DeadLock {
    public static void main(String[] args) {
        new Makeup(0,"灰姑凉").start();
        new Makeup(1,"白雪公主").start();
    }

}

//口红
class Lipstick{

}

//镜子
class Mirror {

}

class Makeup extends Thread {

    //需要的资源只有一份,用static来保证只有一份
    static Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();

    int choice;
    String girlName;

    Makeup(int choice, String girlName) {
        this.choice = choice;
        this.girlName = girlName;
    }

    @Override
    public void run() {
        try {
            makeup();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void makeup() throws InterruptedException {
        if (choice == 0) {
            synchronized (lipstick) {
                System.out.println(this.girlName + "获得了口红的锁");
                Thread.sleep(1000);
                synchronized (mirror) {
                    System.out.println(this.girlName + "获得了镜子的锁");
                }
            }
        } else {
            synchronized (mirror) {
                System.out.println(this.girlName + "获得了镜子的锁");
                Thread.sleep(1000);
                synchronized (lipstick) {
                    System.out.println(this.girlName + "获得了口红的锁");
                }
            }
        }
    }
}
避免死锁
package com.yeyue.thread;

public class DeadLock {
    public static void main(String[] args) {
        new Makeup(0,"灰姑凉").start();
        new Makeup(1,"白雪公主").start();
    }

}

//口红
class Lipstick{

}

//镜子
class Mirror {

}

class Makeup extends Thread {

    //需要的资源只有一份,用static来保证只有一份
    static Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();

    int choice;
    String girlName;

    Makeup(int choice, String girlName) {
        this.choice = choice;
        this.girlName = girlName;
    }

    @Override
    public void run() {
        try {
            makeup();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void makeup() throws InterruptedException {
        if (choice == 0) {
            synchronized (lipstick) {
                System.out.println(this.girlName + "获得了口红的锁");
                Thread.sleep(1000);
                }
            synchronized (mirror) {
                System.out.println(this.girlName + "获得了镜子的锁");
            }
        } else {
            synchronized (mirror) {
                System.out.println(this.girlName + "获得了镜子的锁");
                Thread.sleep(1000);
                }
            synchronized (lipstick) {
                System.out.println(this.girlName + "获得了口红的锁");
            }
        }
    }
}
synchronized与lock的对比
  • lock是显示锁(手动开启和关闭锁,别忘记关锁)synchronized是隐式锁,除了作用域自动释放

  • lock只有代码块锁,synchronized有代码块锁和方法锁

  • 使用lock锁,jvm将花费较少的时间来调度线程,性能更好。而且具有更好的扩展性(提供更多的子类)

  • 优先使用顺序:

    lock>同步代码块(已经进入方法体,分配了相应资源)>同步方法(在方法体之外)

    实例
    package com.yeyue.thread;
    
    import java.util.concurrent.locks.ReentrantLock;
    
    public class TestLock {
        public static void main(String[] args) {
            TestLock2 testLock2 = new TestLock2();
    
            new Thread(testLock2).start();
            new Thread(testLock2).start();
            new Thread(testLock2).start();
        }
    }
    
    class TestLock2 implements Runnable{
    
        int ticketNums = 10;
        //定义lock锁
        private final ReentrantLock lock = new ReentrantLock();
    
        @Override
        public void run() {
            while (true){
                try{
                    lock.lock();
                    if(ticketNums>0){
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(ticketNums--);
                    }else {
                        break;
                    }
                }finally {
                    lock.unlock();
                }
            }
        }
    }
    
生产者消费者模型–>利用缓冲区解决:管程法
package com.yeyue.thread;

//测试:生产者消费者模型-->利用缓冲区解决:管程法

//生产者,消费者,产品,缓冲区
public class TestPC {
    public static void main(String[] args) {
        SynContainer container = new SynContainer();

        new Productor(container).start();
        new Consumer(container).start();

    }
}

//生产者
class Productor extends Thread{
    SynContainer container;

    public Productor(SynContainer container){
        this.container = container;
    }

    //生产
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            container.push(new Chicken(i));
            System.out.println("生产了"+i+"只鸡");
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

//消费者
class Consumer extends Thread{
    SynContainer container;

    public Consumer(SynContainer container){
        this.container = container;
    }

    //消费
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消费了-->"+container.pop().id+"只鸡");
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

//产品
class Chicken{
    int id ; //产品ID

    public Chicken(int id) {
        this.id = id;
    }
}

//缓冲区
class SynContainer {

    //容器大小
    Chicken[] chickens = new Chicken[10];
    //容器计数器
    int count = 0;


    //生产者放入产品
    public synchronized void push(Chicken chicken){
        //如果产品满了,就需要生产者等待消费者消费
        if(count==chickens.length) {
            //通知消费者消费,生产等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果没有满,我们就需要丢入产品
        chickens[count]=chicken;
        count++;

        //可以通知消费者消费了
        this.notifyAll();
    }

    //消费者消费产品
    public synchronized Chicken pop(){
        //判断能否消费
        if(count==0){
            //等待生产者生产,消费者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //如果可以消费
        count--;
        Chicken chicken = chickens[count];

        //吃完了
        this.notifyAll();
        return chicken;
    }












}
测试:生产者消费者模型2–>信号灯法
package com.yeyue.thread;

//测试:生产者消费者模型2-->信号灯法
public class TestPC2 {
    public static void main(String[] args) {
        TV tv = new TV();
        new Player(tv).start();
        new Watcher(tv).start();
    }
}

//生产者:演员
class Player extends Thread{
    TV tv;
    public Player(TV tv){
        this.tv = tv;
    }

    //表演节目
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if(i%2==0){
                this.tv.play("快乐大本营");
            }else{
                this.tv.play("抖音:记录美好生活");
            }
        }
    }
}

//消费者:观众
class Watcher extends Thread{
    TV tv;
    public Watcher(TV tv){
        this.tv = tv;
    }

    //观看
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            tv.watch();
        }
    }
}

//产品:节目
class TV {
    //演员表演,观众等待 T
    //观众观看,演员等待 F
    String voice; //表演的节目
    boolean flag = true;

    //表演
    public synchronized void play(String voice){

        //等待观众观看
        if (!flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("演员表演了:" + voice);

        this.notifyAll(); //通知观众观看
        this.voice = voice;
        this.flag = !this.flag;
    }

    //观看
    public synchronized  void watch(){
        if(flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("观看了"+voice);

        this.notifyAll(); //通知演员表演
        this.flag = !this.flag;
    }

}
线程池
package com.yeyue.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TestPool {
    public static void main(String[] args) {
        //1、创建服务,创建线程池
        //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{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}
#include #include #include #include #include //定义一些常量; //本程序允许的最大临界区数; #define MAX_BUFFER_NUM 10 //秒到微秒的乘法因子; #define INTE_PER_SEC 1000 //本程序允许的生产和消费线程的总数; #define MAX_THREAD_NUM 64 //定义一个结构,记录在测试文件中指定的每一个线程的参数 struct ThreadInfo { int serial; //线程序列号 char entity; //是P还是C double delay; //线程延迟 int thread_request[MAX_THREAD_NUM]; //线程请求队列 int n_request; //请求个数 }; //全局变量的定义 //临界区对象的声明,用于管理缓冲区的互斥访问; int Buffer_Critical[MAX_BUFFER_NUM]; //缓冲区声明,用于存放产品; ThreadInfo Thread_Info[MAX_THREAD_NUM]; //线程信息数组; HANDLE h_Thread[MAX_THREAD_NUM]; //用于存储每个线程句柄的数组; HANDLE empty_semaphore; //一个信号量; HANDLE h_mutex; //一个互斥量; HANDLE h_Semaphore[MAX_THREAD_NUM]; //生产者允许消费者开始消费的信号量; CRITICAL_SECTION PC_Critical[MAX_BUFFER_NUM]; DWORD n_Thread = 0; //实际的线程的数目; DWORD n_Buffer_or_Critical; //实际的缓冲区或者临界区的数目; //生产消费及辅助函数的声明 void Produce(void *p); void Consume(void *p); bool IfInOtherRequest(int); int FindProducePositon(); int FindBufferPosition(int); int main(int argc, char **argv) { //声明所需变量; DWORD wait_for_all; ifstream inFile; if (argc!=2) { printf("Usage:%s \n",argv[0]); return 1; } //初始化缓冲区; for(int i=0;i< MAX_BUFFER_NUM;i++) Buffer_Critical[i] = -1; //初始化每个线程的请求队列; for(int j=0;j<MAX_THREAD_NUM;j++) { for(int k=0;k<MAX_THREAD_NUM;k++) Thread_Info[j].thread_request[k] = -1; Thread_Info[j].n_request = 0; } //初始化临界区; for(i =0;i> n_Buffer_or_Critical; inFile.get(); // 读取测试文件中的空格,将文件指针指向下一行; printf("输入文件是:\n"); //回显获得的缓冲区的数目信息; printf("%d \n",(int) n_Buffer_or_Critical); //提取每个线程的信息到相应数据结构中; while(inFile){ inFile >> Thread_Info[n_Thread].serial; inFile >> Thread_Info[n_Thread].entity; inFile >> Thread_Info[n_Thread].delay; char c; inFile.get(c); while(c!='\n'&& !inFile.eof()) { inFile>> Thread_Info[n_Thread].thread_request[Thread_Info[n_Thread].n_request++]; inFile.get(c); } n_Thread++; } //回显获得的线程信息,便于确认正确性; for(j=0;j<(int) n_Thread;j++) { int Temp_serial = Thread_Info[j].serial; char Temp_entity = Thread_Info[j].entity; double Temp_delay = Thread_Info[j].delay; printf(" \nthread%2d %c %f ",Temp_serial,Temp_entity,Temp_delay); int Temp_request = Thread_Info[j].n_request; for(int k=0;k<Temp_request;k++) printf(" %d ", Thread_Info[j].thread_request[k]); cout<<endl; } printf("\n\n"); //创建在模拟过程中几个必要的信号量 empty_semaphore = CreateSemaphore(NULL,n_Buffer_or_Critical,n_Buffer_or_Critical, "semaphore_for_empty"); h_mutex = CreateMutex(NULL,FALSE,"mutex_for_update"); //下面这个循环用线程的ID号来为相应生产线程的产品读写时所 //使用的同步信号量命名; for(j=0;j<(int)n_Thread;j++) { char lp[]="semaphore_for_produce_"; int temp =j; while(temp){ char c = (char)(temp%10); strcat(lp,&c); temp/=10; } h_Semaphore[j+1]=CreateSemaphore(NULL,0,n_Thread,lp); } //创建生产者消费者线程; for(i =0;i< (int) n_Thread;i++) { if(Thread_Info[i].entity =='P') h_Thread[i]= CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)(Produce), &(Thread_Info[i]),0,NULL); else h_Thread[i]=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)(Consume), &(Thread_Info[i]),0,NULL); } //主程序等待各个线程的动作结束; wait_for_all = WaitForMultipleObjects(n_Thread,h_Thread,TRUE,-1); printf(" \n \nALL Producer and consumer have finished their work. \n"); printf("Press any key to quit!\n"); _getch(); return 0; } //确认是否还有对同一产品的消费请求未执行; bool IfInOtherRequest(int req) { for(int i=0;i<n_Thread;i++) for(int j=0;j<Thread_Info[i].n_request;j++) if(Thread_Info[i].thread_request[j] == req) return TRUE; return FALSE; } //找出当前可以进行产品生产的空缓冲区位置; int FindProducePosition() { int EmptyPosition; for (int i =0;i<n_Buffer_or_Critical;i++) if(Buffer_Critical[i] == -1) { EmptyPosition = i; //用下面这个特殊值表示本缓冲区正处于被写状态; Buffer_Critical[i] = -2; break; } return EmptyPosition; } //找出当前所需生产者生产的产品的位置; int FindBufferPosition(int ProPos) { int TempPos; for (int i =0 ;iserial; m_delay = (DWORD)(((ThreadInfo*)(p))->delay *INTE_PER_SEC); Sleep(m_delay); //开始请求生产 printf("Producer %2d sends the produce require.\n",m_serial); //互斥访问下一个可用于生产的空临界区,实现写写互斥; wait_for_mutex = WaitForSingleObject(h_mutex,-1); //确认有空缓冲区可供生产,同时将空位置数empty减1;用于生产者消费者的同步; //若没有则一直等待,直到消费者进程释放资源为止; wait_for_semaphore = WaitForSingleObject(empty_semaphore,-1); int ProducePos = FindProducePosition(); ReleaseMutex(h_mutex); //生产者在获得自己的空位置并做上标记后,以下的写操作在生产者之间可以并发; //核心生产步骤中,程序将生产者的ID作为产品编号放入,方便消费者识别; printf("Producer %2d begin to produce at position %2d.\n",m_serial,ProducePos); Buffer_Critical[ProducePos] = m_serial; printf("Producer %2d finish producing :\n ",m_serial); printf(" position[ %2d ]:%3d \n\n" ,ProducePos,Buffer_Critical[ProducePos]); //使生产者写的缓冲区可以被多个消费者使用,实现读写同步; ReleaseSemaphore(h_Semaphore[m_serial],n_Thread,NULL); } //消费者进程 void Consume(void * p) { //局部变量声明; DWORD wait_for_semaphore,m_delay; int m_serial,m_requestNum; //消费者的序列号和请求的数目; int m_thread_request[MAX_THREAD_NUM]; //本消费线程的请求队列; //提取本线程的信息到本地; m_serial = ((ThreadInfo*)(p))->serial; m_delay = (DWORD)(((ThreadInfo*)(p))->delay *INTE_PER_SEC); m_requestNum = ((ThreadInfo *)(p))->n_request; for (int i = 0;ithread_request[i]; Sleep(m_delay); //循环进行所需产品的消费 for(i =0;ithread_request[i] =-1; if(!IfInOtherRequest(m_thread_request[i])) { Buffer_Critical[BufferPos] = -1; //-1标记缓冲区为空; printf("Consumer %2d finish consuming %2d:\n ",m_serial,m_thread_request[i]); printf(" position[ %2d ]:%3d \n\n" ,BufferPos,Buffer_Critical[BufferPos]); ReleaseSemaphore(empty_semaphore,1,NULL); } else { printf("Consumer %2d finish consuming product %2d\n\n ",m_serial,m_thread_request[i]); } //离开临界区 LeaveCriticalSection(&PC_Critical[BufferPos]); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值