死锁
两个线程同时拿着对方需要的资源不释放,而形成的相互等待,就是死锁
管程法
package 多线程.管程法;
/*
*生产者负责生产
*消费者负责消费
*缓冲区作为缓存产品的池子
* 四个类 生产者 消费者 产品 缓冲池
* 生产者消费者使用线程,缓冲池操作产品
*/
public class Test {
public static void main(String[] args) {
chickenPond cp = new chickenPond();
new Producer(cp).start();
new consumer(cp).start();
}
}
//生产者
class Producer extends Thread {
chickenPond cp;
public Producer(chickenPond cp) {
this.cp = cp;
}
@Override
public void run() {
for (int i = 1; i < 100; i++) {
cp.push(new Chicken(i));
System.out.println("生产了第" + i + "只鸡");
}
}
}
//消费者
class consumer extends Thread {
chickenPond cp;
public consumer(chickenPond cp) {
this.cp = cp;
}
@Override
public void run() {
for (int i = 1; i < 100; i++) {
System.out.println("消费了第" + cp.pop().ID + "只鸡");
}
}
}
//商品 炸鸡
class Chicken{
int ID;
public Chicken(int ID) {
this.ID = ID;
}
}
//缓冲区 炸鸡池
class chickenPond{
//池子最大存储100只鸡
Chicken[] chickens = new Chicken[10];
//容器计数器
int count = 0;
//生产者生产一只炸鸡
public synchronized void push(Chicken chicken){
//如果鸡满了就不生产鸡
while (count == chickens.length){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
chickens[count] = chicken;
count++;
this.notifyAll();
}
//消费者买走一只炸鸡
public synchronized Chicken pop(){
//如果没有鸡了就叫生产者生产
while (count == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//有鸡就将鸡给消费者
count--;
Chicken chicken = chickens[count];
this.notifyAll();
return chicken;
}
}
信号灯法
package 多线程.信号灯法;
/*
*两个线程运行次数要一样,不然无法相互转换造成死锁
*/
public class Test {
public static void main(String[] args) {
C c = new C();
new A(c).start();
new B(c).start();
}
}
class A extends Thread{
C c;
public A(C c){
this.c = c;
}
@Override
public void run() {
for (int i = 1; i < 100; i++) {
c.RedLight(i);
}
}
}
class B extends Thread{
C c;
public B(C c){
this.c = c;
}
@Override
public void run() {
for (int i = 1; i < 100; i++) {
c.GreenLight(i);
}
}
}
class C{
int num = 2;
//标志位判断等待线程
boolean flag = true;
public synchronized void RedLight(int ID){
if (flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("当前第A" + ID + "辆车通过");
this.flag = !flag;
this.notifyAll();
}
public synchronized void GreenLight(int ID){
if (!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("当前第B" + ID + "辆车通过");
this.flag = !flag;
this.notifyAll();
}
}
线程池
package 多线程.线程池;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Test {
public static void main(String[] args) {
ExecutorService es = Executors.newFixedThreadPool(10);
//开启线程
es.execute(new T1());
es.execute(new T1());
es.execute(new T1());
es.execute(new T1());
//关闭线程
es.shutdown();
}
}
class T1 extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}