#include<stdio.h>#include<string.h>#include<unistd.h>#include<pthread.h>#include<fcntl.h>#include<sys/stat.h>#include<stdlib.h>#include<time.h>pthread_mutex_t mtx1,mtx2;void*thread1(void* arg){printf("child get mtx1.........\n");pthread_mutex_lock(&mtx1);printf("child get mtx1 success!\n");sleep(1);printf("child get mtx2.........\n");pthread_mutex_lock(&mtx2);printf("child get mtx2 success!\n");pthread_mutex_unlock(&mtx1);pthread_mutex_unlock(&mtx2);}intmain(int argc,char* argv[]){pthread_mutex_init(&mtx1,NULL);pthread_mutex_init(&mtx2,NULL);pthread_t tid;pthread_create(&tid,NULL,thread1,NULL);printf("main get mtx2.........\n");pthread_mutex_lock(&mtx2);printf("main get mtx2 success!\n");sleep(1);printf("main get mtx1.........\n");pthread_mutex_lock(&mtx1);printf("main get mtx1 success!\n");pthread_mutex_unlock(&mtx2);pthread_mutex_unlock(&mtx1);return0;}
死锁产生的四个必要条件
1.互斥条件:必须得有多个互斥变量
2.持有并等待条件:A持有锁1并等待B锁2解锁,B持有锁2并等待A锁1解锁
3.不可剥夺条件:必须一直阻塞
4.环路等待条件
避免死锁
1.不加锁(不太现实奥)
2.锁的力度控制:尽量减少持有锁的事件,降低死锁发生概率
3.资源有序分配:破坏环路条件1 2 1 2
4.重试机制:破坏不可剥夺条件,一般为非阻塞的trylock
#include<stdio.h>#include<string.h>#include<unistd.h>#include<pthread.h>#include<fcntl.h>#include<sys/stat.h>#include<stdlib.h>#include<time.h>#include<errno.h>pthread_mutex_t mtx1,mtx2;void*thread1(void* arg){while(1){printf("child get mtx1.........\n");pthread_mutex_lock(&mtx1);printf("child get mtx1 success!\n");sleep(1);printf("child get mtx2.........\n");int ret =pthread_mutex_trylock(&mtx2);if(ret !=0&& ret == EBUSY){pthread_mutex_unlock(&mtx1);printf("child free mtx1\n");continue;}printf("child get mtx2 success!\n");pthread_mutex_unlock(&mtx1);pthread_mutex_unlock(&mtx2);returnNULL;}}intmain(int argc,char* argv[]){pthread_mutex_init(&mtx1,NULL);pthread_mutex_init(&mtx2,NULL);pthread_t tid;pthread_create(&tid,NULL,thread1,NULL);printf("main get mtx2.........\n");pthread_mutex_lock(&mtx2);printf("main get mtx2 success!\n");sleep(1);printf("main get mtx1.........\n");pthread_mutex_lock(&mtx1);printf("main get mtx1 success!\n");pthread_mutex_unlock(&mtx2);pthread_mutex_unlock(&mtx1);pthread_exit(NULL);return0;}
二、贪心算法之区间调度问题
0.计算一个区间集合中无重复的区间的最大数量(模板)
public int intervalSchedule(int[][] intvs) {if (intvs.length 0) return 0;// 按 end 升序排序Arrays.sort(intvs, (a, b) -> Integer.compare(a[1], b[1]));// 至少有一个区间不相交in…
!! 有get/set方法的情况基本就是说要搞个私有属性,不直接对外开放;
构造器
Person p new Person();
//其中的Person();就是构造器;---造对象;Constructor–建设者,建造者;
作用
搭配new 创建类的&…