JUC并发编程笔记

JUC并发编程

一 多线程的实现方式

① 继承Thread类

public class ThreadDemo {
    public static void main(String[] args) {
        // 4.创建Thread类的子类对象
        MyThread myThread = new MyThread();
        // 5.调用start()方法开启线程
        myThread.start();
        for (int i = 0; i < 100; i++) {
            System.out.println("我是主线程" + i);
        }
    }
}

/**
 * 1. 新建MyThread类继承Thread类
 */
class MyThread extends Thread {
    /**
     * 2.重写run方法
     */
    @Override
    public void run() {
        // 3.将要执行的代码写在run方法中
        for (int i = 0; i < 100; i++) {
            System.out.println("我是线程" + i);
        }
    }
}

② 实现Runnable接口

public class ThreadDemo2 {
    public static void main(String[] args) {
        // 4.创建Runnable的子类对象
        MyRunnable myRunnable = new MyRunnable();
        // 5.将子类对象当做参数传递给Thread的构造函数,并开启线程
        new Thread(myRunnable).start();
        for (int i = 0; i < 1000; i++) {
            System.out.println("我是主线程" + i);
        }
    }
}

/**
 * 1.MyRunnable实现Runnable接口
 */
class MyRunnable implements Runnable {
    /**
     * 2.重写run方法
     */
    @Override
    public void run() {
        // 3.将要执行的代码写在run方法中
        for (int i = 0; i < 1000; i++) {
            System.out.println("我是线程" + i);
        }
    }
}

③ 通过Callable和FutureTask创建线程

public class ThreadDemo3 {
    public static void main(String[] args) {
        // 3.创建callable接口实现类的对象
        MyCallable m = new MyCallable();
        // 4.将此callable的对象作为参数传入到FutureTask构造器中,创建FutureTask的对象

        FutureTask futureTask = new FutureTask(m);
        // 5.将FutureTask对象作为参数传递到Thread类的构造器中,创建Thread对象,并调用start()方法
        // FutureTask类继承了Runnable接口
        new Thread(futureTask).start();

        // 6.获取callable接口中call方法的返回值
        try {
            // get()方法返回值即为FutureTask构造器参数callable实现类重写的call方法的返回值
            Object sum = futureTask.get();
            System.out.println("总和是:" + sum);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

/**
 * 1.创建一个实现Callable接口的实现类
 */
class MyCallable implements Callable {
    /**
     * 实现call方法,将此线程需要执行的操作声明在call()中
     *
     * @return
     * @throws Exception
     */
    @Override
    public Object call() throws Exception {
        int sum = 0;
        for (int i = 1; i <= 100; i++) {
            System.out.println(i);
            sum += i;
        }
        return sum;
    }
}

二 线程间通信

① 虚假唤醒问题

多线程环境下,有多个线程在等待,若有一个线程唤醒了他们,由于把所有线程都唤醒了,但是只有其中一部分是有用的唤醒操作,其余的唤醒都是无用功,对于不应该被唤醒的线程而言,便是虚假唤醒。

A: synchronized版本实现
package com.lzp.juc.thread;

/**
 * 1.题目:
 * 现在两个线程,可以操作初始值为0的一个变量,实现一个线程对该变量加1,
 * 一个线程对该变量减1,交替执行,来10轮,变量的初始值为0
 * 2.思想:
 * 1.在高内聚低耦合的前提下,线程->操作->资源类
 * 2.判断操作唤醒[生产消费中]
 * 3.多线程交互中,必须要放置多线程的虚假唤醒,也即(判断使用while,不能使用if)
 *
 * @author lzp
 * @date 2022/6/26 23:15:41
 */
public class ThreadWaitNotifyDemo {
    public static void main(String[] args) {
        AirCondition airCondition = new AirCondition();
        new Thread(() -> {
            for (int i = 1; i < 11; i++) {
                airCondition.increment();
            }
        }, "线程A").start();

        new Thread(() -> {
            for (int i = 1; i < 11; i++) {
                airCondition.decrement();
            }
        }, "线程B").start();
        new Thread(() -> {
            for (int i = 1; i < 11; i++) {
                airCondition.increment();
            }
        }, "线程C").start();
        new Thread(() -> {
            for (int i = 1; i < 11; i++) {
                airCondition.decrement();
            }
        }, "线程D").start();
    }
}

class AirCondition {

    private int number = 0;

    /**
     * 变量加1
     */
    public synchronized void increment() {
        // 1.判断
        if (number != 0) {
        while (number != 0) {
            try {
                // wait方法在哪等待就在哪里唤醒,wait方法应该始终再循环中使用
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 2.干活
        number++;
        System.out.println(Thread.currentThread().getName() + ":" + number);
        //3.唤醒
        this.notifyAll();
    }

    /**
     * 变量减1
     */
    public synchronized void decrement() {
        if (number == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        number--;
        System.out.println(Thread.currentThread().getName() + ":" + number);
        this.notifyAll();
    }

}

执行结果

线程A:1
线程B:0
线程A:1
线程B:0
线程A:1
线程B:0
线程A:1
线程B:0
线程A:1
线程B:0
线程A:1
线程B:0
线程A:1
线程C:2
线程A:3
线程B:2
线程B:1
线程B:0
线程A:1
线程D:0
线程C:1
线程D:0
线程A:1
线程B:0
线程D:-1
线程D:-2
线程D:-3
线程D:-4
线程D:-5
线程D:-6
线程D:-7
线程D:-8
线程C:-7

如何避免虚假唤醒问题?

使用while循环去循环判断一个条件,而不是使用if只判断一次条件;即wait()要在while循环中。

调整后

package com.lzp.juc.thread;

/**
 * 1.题目:
 * 现在两个线程,可以操作初始值为0的一个变量,实现一个线程对该变量加1,
 * 一个线程对该变量减1,交替执行,来10轮,变量的初始值为0
 * 2.思想:
 * 1.在高内聚低耦合的前提下,线程->操作->资源类
 * 2.判断操作唤醒[生产消费中]
 * 3.多线程交互中,必须要放置多线程的虚假唤醒,也即(判断使用while,不能使用if)
 *
 * @author lzp
 * @date 2022/6/26 23:15:41
 */
public class ThreadWaitNotifyDemo {
    public static void main(String[] args) {
        AirCondition airCondition = new AirCondition();
        new Thread(() -> {
            for (int i = 1; i < 11; i++) {
                airCondition.increment();
            }
        }, "线程A").start();

        new Thread(() -> {
            for (int i = 1; i < 11; i++) {
                airCondition.decrement();
            }
        }, "线程B").start();
        new Thread(() -> {
            for (int i = 1; i < 11; i++) {
                airCondition.increment();
            }
        }, "线程C").start();
        new Thread(() -> {
            for (int i = 1; i < 11; i++) {
                airCondition.decrement();
            }
        }, "线程D").start();
    }
}

class AirCondition {

    private int number = 0;

    /**
     * 变量加1
     */
    public synchronized void increment() {
        // 1.判断
        /*if (number != 0) {*/
        while (number != 0) {
            try {
                // wait方法在哪等待就在哪里唤醒,wait方法应该始终再循环中使用
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 2.干活
        number++;
        System.out.println(Thread.currentThread().getName() + ":" + number);
        //3.唤醒
        this.notifyAll();
    }

    /**
     * 变量减1
     */
    public synchronized void decrement() {
        /*if (number == 0) {*/
        while (number == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        number--;
        System.out.println(Thread.currentThread().getName() + ":" + number);
        this.notifyAll();
    }

}
B: Lock版本实现
package com.lzp.juc.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用Lock代替synchronized来实现
 *
 * @author lzp
 * @date 2022/6/26 23:50:48
 */
public class ThreadWaitNotifyDemo2 {
    public static void main(String[] args) {
        AirCondition2 airCondition2 = new AirCondition2();
        new Thread(() -> {
            for (int i = 1; i < 11; i++) {
                airCondition2.increment();
            }
        }, "线程A").start();

        new Thread(() -> {
            for (int i = 1; i < 11; i++) {
                airCondition2.decrement();
            }
        }, "线程B").start();
        new Thread(() -> {
            for (int i = 1; i < 11; i++) {
                airCondition2.increment();
            }
        }, "线程C").start();
        new Thread(() -> {
            for (int i = 1; i < 11; i++) {
                airCondition2.decrement();
            }
        }, "线程D").start();
    }
}

class AirCondition2 {
    private int number = 0;
    // 定义Lock锁对象
    private final Lock lock = new ReentrantLock();
    private final Condition condition = lock.newCondition();

    // 生产者,如果number=0就 number++
    public void increment() {
        // 加锁
        lock.lock();
        try {
            // 1.判断
            while (number != 0) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 2.干活
            number++;
            System.out.println(Thread.currentThread().getName() + ":" + number);
            // 3.唤醒
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 解锁
            lock.unlock();
        }
    }

    // 消费者,如果number=1,就 number--
    public void decrement() {
        // 加锁
        lock.lock();
        try {
            // 1.判断
            while (number == 0) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 2.干活
            number--;
            System.out.println(Thread.currentThread().getName() + ":" + number);
            // 3.唤醒
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 解锁
            lock.unlock();
        }
    }
}

② 线程间定制化通信

/**
 * 线程间定制化通信
 * 启动三个线程,按照如下要求操作:
 * AA线程打印5次,BB线程打印10次,CC线程打印15次
 * 执行10轮
 *
 * @author lzp
 * @date 2022/6/27 23:37:59
 */
public class ThreadCustomizedDemo {
    public static void main(String[] args) {
        CustomizeResource resource = new CustomizeResource();
        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                resource.print5(i);
            }
        }, "AA").start();
        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                resource.print10(i);
            }
        }, "BB").start();
        new Thread(() -> {
            for (int i = 1; i <= 10; i++) {
                resource.print15(i);
            }
        }, "CC").start();
    }
}

/**
 * 资源类
 */
class CustomizeResource {
    // 定义flag
    private int flag = 1;
    // 创建lock锁
    private Lock lock = new ReentrantLock();
    // 创建三个condition,指定唤醒对应线程
    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private Condition c3 = lock.newCondition();

    /**
     * 打印5次
     *
     * @param loop 轮数
     */
    public void print5(int loop) {
        // 上锁
        lock.lock();
        try {
            // 判断flag,flag!=1时,线程等待
            while (flag != 1) {
                try {
                    c1.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 干活,打印5轮
            for (int i = 1; i <= 5; i++) {
                System.out.println(Thread.currentThread().getName() + " :: " + i + ", 轮数 :" + loop);
            }
            // 修改标志flag
            flag = 2;
            // 通知B线程
            c2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 解锁
            lock.unlock();
        }
    }

    /**
     * 打印10次
     *
     * @param loop 轮数
     */
    public void print10(int loop) {
        // 上锁
        lock.lock();
        try {
            // 判断flag,flag!=2时,线程等待
            while (flag != 2) {
                try {
                    c2.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 干活,打印10轮
            for (int i = 1; i <= 10; i++) {
                System.out.println(Thread.currentThread().getName() + " :: " + i + ", 轮数 :" + loop);
            }
            // 修改标志flag
            flag = 3;
            // 通知C线程
            c3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 解锁
            lock.unlock();
        }
    }

    /**
     * 打印15次
     *
     * @param loop 轮数
     */
    public void print15(int loop) {
        // 上锁
        lock.lock();
        try {
            // 判断flag,flag!=3时,线程等待
            while (flag != 3) {
                try {
                    c3.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 干活,打印15轮
            for (int i = 1; i <= 15; i++) {
                System.out.println(Thread.currentThread().getName() + " :: " + i + ", 轮数 :" + loop);
            }
            // 修改标志flag
            flag = 1;
            // 通知A线程
            c1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 解锁
            lock.unlock();
        }
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值