Java多线程以及三种实现方式

线程简介

  • 程序Process(静态)、进程(动态)、线程Thread
    程序:在操作系统中运行的程序就是进程,比如你的QQ,播放器,游戏,IDE等等
    进程:执行程序的一次过程,是系统资源分配的单位,main()
    线程:一个进程有若干线程,一个进程至少有一个线程,是CPU调度和执行的单位
  • 一些概念
  1. 线程就是独立的执行路径;
  2. 在程序运行时,即使没有自己创建线程,后台也会有多个线程,如主线程,gc线程;
  3. main()称之为主线程,为系统的入口,用于执行整个程序;
  4. 在一个进程中,如果开辟了多个线程,线程的运行由调度器安排调度,调度器是与操作系统紧密相关的,先后顺序是不能认为的干预的。
  5. 对同一份资源操作时,会存在资源抢夺的问题,需要加入并发控制;
  6. 线程会带来额外的开销,如cpu调度时间,并发控制开销。
  7. 每个线程在自己的工作内存交互,内存控制不当会造成数据不一致
  • 多线程
    一个游戏,一堆玩家同时在线

线程实现※

1.Thread class:继承Thread类

//创建线程方式一:继承Thread类,重写run()方法,调用start开启线程

//总结:注意,线程开启不一定立即执行,由CPU调度执行

public class TestThread1 extends Thread {
    @Override
    public void run() {
        //run方法线程体
        for (int i = 0; i < 200; i++) {
            System.out.println("我在看代码---" + i);
        }
    }

    public static void main(String[] args) {
        //main线程 主线程

        //创建一个线程对象
        TestThread1 testThread1 = new TestThread1();

        //调用start()方法
        testThread1.start();

        for (int i = 0; i < 200; i++) {
            System.out.println("我在学习多线程---"+i);
        }
    }
}

部分输出

//多线程下载
public class TestThread2 extends Thread{
    private String url;

    public TestThread2(String url) {
        this.url = url;
    }

    //下载图片线程的执行体
    @Override
    public void run() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.download(url);
    }

    public static void main(String[] args) {
        TestThread2 t1 = new TestThread2("URL1");
        TestThread2 t2 = new TestThread2("URL2");
        TestThread2 t3 = new TestThread2("URL3");

        //同时执行,不是按顺序的
        t1.start();
        t2.start();
        t3.start();
    }
}

//下载器
class WebDownloader{
    //下载方法
    public void download(String url){}
}

2.Runnable接口,实现Runnable接口(推荐使用的方法)

//创建线程方式二:实现runnable接口,重写run()方法,
//执行线程需要丢人runnable接口实现类,调用start方法
public class TestThread3 implements Runnable{
    @Override
    public void run() {
        //run方法线程体
        for (int i = 0; i < 200; i++) {
            System.out.println("我在看代码---" + i);
        }
    }

    public static void main(String[] args) {
        //创建runnable接口的实现类对象
        TestThread3 testThread3 = new TestThread3();
        //创建线程对象,通过线程对象来开启我们的线程,代理
        //Thread thread = new Thread();
        //thread.start();
        new Thread(testThread3).start();

        for (int i = 0; i < 200; i++) {
            System.out.println("我在学习多线程---"+i);
        }
    }
}
  • 并发问题
//多个线程操作同一个对象
//买火车票

//发现问题:多个线程操作同一个资源,线程不安全,数据紊乱
public class TestThread4 implements Runnable {

    //票数
    private int ticketNums = 10;

    @Override
    public void run() {
        while (true){
            if (ticketNums<=0){
                break;
            }

            try { //模拟延时
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(Thread.currentThread().getName()+"-->拿到了第"+ticketNums--+"张票");
        }
    }

    public static void main(String[] args) {
        TestThread4 ticket = new TestThread4();

        new Thread(ticket,"小明").start();
        new Thread(ticket,"老师").start();
        new Thread(ticket,"黄牛").start();
    }
}
  • 龟兔赛跑
//模拟龟兔赛跑
public class Race implements Runnable{

    //胜利者
    private static String winner;

    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {

            //模拟兔子休息
            if (Thread.currentThread().getName().equals("兔子") && i%50==0){
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            //判断比赛是否结束
            boolean flag = gameOver(i);
            //如果比赛结束了,就停止程序
            if (flag){
                break;
            }

            System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");
        }
    }

    //判断是否完成比赛
    private boolean gameOver(int steps){
        //判断是否有胜利者
        if (winner!=null){
            return true;
        }{
            if (steps>=100){
                winner = Thread.currentThread().getName();
                System.out.println(winner+"赢了!");
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Race race = new Race();

        new Thread(race,"兔子").start();
        new Thread(race,"乌龟").start();
    }
}

3.Callable接口:实现Callable接口

import java.util.concurrent.*;

//线程创建方式三:实现Callable接口
public class TestCallable implements Callable<Boolean> { //必须有返回值

    private String url;

    public TestCallable(String url) {
        this.url = url;
    }

    //下载图片线程的执行体
    @Override
    public Boolean call() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.download(url);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable t1 = new TestCallable("URL1");
        TestCallable t2 = new TestCallable("URL2");
        TestCallable t3 = new TestCallable("URL3");

        //创建执行服务,线程池
        ExecutorService ser = Executors.newFixedThreadPool(3);

        //提交执行
        Future<Boolean> r1 = ser.submit(t1);
        Future<Boolean> r2 = ser.submit(t2);
        Future<Boolean> r3 = ser.submit(t3);

        //获取结果
        boolean rs1 = r1.get();
        boolean rs2 = r2.get();
        boolean rs3 = r3.get();

        //关闭服务
        ser.shutdown();

    }
}

//下载器
class WebDownloader{
    //下载方法
    public void download(String url){}
}

静态代理

//静态代理模式
//真实对象和代理对象都要实现同一个接口
//代理对象要代理真实对象
//好处:代理对象可以做很多真实对象做不了的事情,真实对象专注于自己的事情
public class StaticProxy {
    public static void main(String[] args) {

        //静态代理 与 线程  相似原理
        //new Thread(()-> System.out.println("我爱你")).start();
        //new WeddingCompany(new You()).HappyMarry();

        //真正结婚的人
        You you = new You();

        //把事情交给代理做
        WeddingCompany weddingCompany = new WeddingCompany(you);
        weddingCompany.HappyMarry();
    }
}

interface Marry{
    void HappyMarry();
}

//真实角色
class You implements Marry{
    @Override
    public void HappyMarry() {
        System.out.println("结婚了");
    }
}

//代理
class WeddingCompany implements Marry{

    //代理真实目标角色
    private Marry target;

    public WeddingCompany(Marry target) {
        this.target = target;
    }

    @Override
    public void HappyMarry() {
        before();
        this.target.HappyMarry(); //真实对象
        after();
    }

    private void after() {
        System.out.println("收尾款");
    }

    private void before() {
        System.out.println("布置现场");
    }
}

Lambda表达式

  • 简化了程序,简洁,只留下逻辑
  • 函数式接口(前提)
    任何接口,如果只包含唯一一个抽象方法,那么它就是一个函数式接口,如
public interface Runnable{
    public abstract void run();
}

对于函数式接口,我们可以通过lambda表达式来创建该接口的对象。

//推导lambda表达式
public class TestLambda1 {

    //3.静态内部类
    static class Like2 implements ILike{
        @Override
        public void lambda() {
            System.out.println("i like lambda2");
        }
    }

    public static void main(String[] args) {
        ILike like = new Like();
        like.lambda();

        like = new Like2();
        like.lambda();

        //4.局部内部类
        class Like3 implements ILike{
            @Override
            public void lambda() {
                System.out.println("i like lambda3");
            }
        }

        like = new Like3();
        like.lambda();

        //5.匿名内部类,没有类的名称,必须借助接口或父类
        like = new ILike() {
            @Override
            public void lambda() {
                System.out.println("i like lambda4");
            }
        };
        like.lambda();

        //6.用lambda简化
        like = ()->{System.out.println("i like lambda5");};
        like.lambda();
        
        //7.只有一行可以不加大括号
        like = ()-> System.out.println("i like lambda5");
        like.lambda();
    }
}

//1.定义一个函数式接口
interface ILike{
    void lambda();
}

//2.实现类
class Like implements ILike{
    @Override
    public void lambda() {
        System.out.println("i like lambda");
    }
}

线程状态

  • 线程方法

  • 线程停止

//测试停止线程
//1.建议线程正常停止--->利用次数,不建议死循环。
//2.建议使用标志位--->设置一个标志位
//3.不要使用stop或都destroy等过时或者JDK不建议使用的方法
public class TestStop implements Runnable{

    //1.设置一个标识位
    private boolean flag = true;

    @Override
    public void run() {
        int i = 0;
        while (flag){
            System.out.println("run...Thread"+i++);
        }
    }

    //2.设置一个公开的方法停止线程,转换标识位
    public void stop(){
        this.flag = false;
    }

    public static void main(String[] args) {
        TestStop testStop = new TestStop();
        new Thread(testStop).start();

        for (int i = 0; i < 1000; i++) {
            System.out.println("main "+i);
            if (i==900){
                //调用我们的stop切换标识位,让线程停止
                testStop.stop();
                System.out.println("线程该停止了");
            }
        }
    }
}
  • 线程休眠
    sleep 1000ms=1s
    每一个对象都有一个锁,sleep不会释放锁
import java.text.SimpleDateFormat;
import java.util.Date;

//模拟倒计时
public class TestSleep2 {

    public static void main(String[] args) {
        //打印当前系统时间
        Date startTime = new Date(System.currentTimeMillis()); //获取系统当前时间
        while (true){
            try {
                Thread.sleep(1000);
                System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
                startTime = new Date(System.currentTimeMillis());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //模拟倒计时
    public static void tenDown() throws InterruptedException {
        int num = 10;
        while (true){
            Thread.sleep(1000);
            System.out.println(num--);
            if (num<=0){
                break;
            }
        }
    }
}
  • 线程礼让(出来重新竞争)
    礼让线程,让当前正在执行的线程暂停,但不阻塞
    将线程从运行状态转为就绪状态
    让cpu重新调度,礼让不一定成功,看CPU心情
//测试礼让
public class TestYield {
    public static void main(String[] args) {
        MyYield myYield = new MyYield();

        new Thread(myYield,"a").start();
        new Thread(myYield,"b").start();
    }
}

class MyYield implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"线程开始执行");
        Thread.yield();
        System.out.println(Thread.currentThread().getName()+"线程停止执行");
    }
}
  • Join插队
    Join合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞
//Join插队,把别人阻塞了,少用
public class TestJoin implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println("线程vip来了 "+i);
        }
    }

    public static void main(String[] args) throws InterruptedException {

        //启动我们的线程
        TestJoin testJoin = new TestJoin();
        Thread thread = new Thread(testJoin);
        thread.start();

        //主线程
        for (int i = 0; i < 1000; i++) {
            if (i==200){
                thread.join(); //插队
            }
            System.out.println("main "+i);
        }
    }
}
  • 线程状态观测
    Thread.State 线程状态。线程可以处于以下状态之一:
    ●NEW 尚未启动的线程处于此状态
    ●RUNNABLE 在Java虛拟机中执行的线程处于此状态
    ●BLOCKED 被阻塞等待监视器锁定的线程处于此状态
    ●WAITING 正在等待另一个线程执行特定动作的线程处于此状态
    ●TIMED WAITING 正在等待另一个线程执行动作达到指定等待时间的线程处于此状态
    ●TERMINATED 已退出的线程处于此状态。
    死亡之后的线程不能再start了
//观察测试线程的状态
public class TestState {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("+++++++");
        });

        //观察状态
        Thread.State state = thread.getState();
        System.out.println(state); //NEW

        //观察启动后
        thread.start(); //启动线程
        state = thread.getState();
        System.out.println(state); //RUNNABLE

        while (state!=Thread.State.TERMINATED){
            Thread.sleep(200);
            state = thread.getState(); //更新线程状态
            System.out.println(state); //输出状态
        }
    }
}
  • 线程优先级(调度概率)
//测试线程优先级 1-10,默认5
public class TestPriority {
    public static void main(String[] args) {
        //主线程默认优先级
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());

        MyPriority myPriority = new MyPriority();

        Thread t1 = new Thread(myPriority);
        Thread t2 = new Thread(myPriority);
        Thread t3 = new Thread(myPriority);
        Thread t4 = new Thread(myPriority);
        Thread t5 = new Thread(myPriority);
        Thread t6 = new Thread(myPriority);

        //先设置优先级,再启动
        t1.start();
        t2.setPriority(1);
        t2.start();
        t3.setPriority(4);
        t3.start();
        t4.setPriority(10);
        t4.start();
        t5.setPriority(8);
        t5.start();
        t6.setPriority(7);
        t6.start();
    }
}

class MyPriority implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
    }
}

输出 优先级高的不一定先跑

main-->5
Thread-0-->5
Thread-3-->10
Thread-2-->4
Thread-4-->8
Thread-5-->7
Thread-1-->1
  • 守护(daemon)线程
    线程分为用户线程守护线程
    虚拟机必须确保用户线程执行完毕
    虚拟机不用等待守护线程执行完毕
    如,后台记录操作日志,监控内存,垃圾回收等待
public class TestDaemon {
    public static void main(String[] args) {
        God god = new God();
        You you = new You();

        Thread thread = new Thread(god);
        thread.setDaemon(true); //默认false,表示用户线程,正常的线程都是用户线程

        thread.start(); //上帝 守护线程启动

        new Thread(you).start(); //你 用户线程启动
        //用户线程结束,守护线程也跟着结束了
    }
}

//上帝
class God implements Runnable{
    @Override
    public void run() {
        while (true){
            System.out.println("上帝保佑着你");
        }
    }
}

//你
class You implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 30000; i++) {
            System.out.println("你开心的活着");
        }
        System.out.println("==goodbye==world==");
    }
}

线程同步※

  • 并发
    多个线程操作同一个资源
    解决:排队,队列
  • 队列和锁
    进去后上锁,解决完了再释放
    由于同一进程的多个线程共享同一块存储空间,在带来方便的同时也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制synchronized,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可.存在以下问题:
    ◆ 一个线程持有锁会导致其他所有需要此锁的线程挂起
    ◆ 在多线程竞争下,加锁,释放锁会导致比较多的上下文切换和调度延时,引起性能问题
    ◆ 如果一个优先级高的线程等待一个优先级低的线程释放锁会导致优先级倒置,引起性能问题

三个不安全的线程案例

  • 不安全的买票
//线程不安全,有重合的,还有负数
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();

        new Thread(station,"小明").start();
        new Thread(station,"老师").start();
        new Thread(station,"黄牛").start();
    }
}

class BuyTicket implements Runnable{

    //票
    private int tickerNums =10;
    boolean flag = true; //外部停止方式

    @Override
    public void run() {
        //买票
        while (flag){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void buy() throws InterruptedException {
        //判断是否有票
        if (tickerNums<=0){
            flag = false;
            return;
        }

        //模拟延时
        Thread.sleep(100);

        //买票
        System.out.println(Thread.currentThread().getName()+"拿到票"+tickerNums--);
    }
}
  • 不安全的取钱
//两个人用同一账户去银行取钱
public class UnsafeBank {
    public static void main(String[] args) {
        //账户
        Account account = new Account("peng",100);

        Drawing byPhone = new Drawing(account,50,"peng-1");
        Drawing byBank = new Drawing(account,100,"peng-2");

        byPhone.start();
        byBank.start();
    }
}

//账户
class Account{
    String name;
    int money;

    public Account() {
    }

    public Account(String name, int money) {
        this.name = name;
        this.money = money;
    }
}

//银行:模拟取款
class Drawing extends Thread{

    Account account; //账户
    int drawingMoney; //取多少钱
    int nowMoney; //还有多少钱

    public Drawing(Account account, int drawingMoney, String name) {
        super(name);
        this.account = account;
        this.drawingMoney = drawingMoney;
    }

    //取钱
    @Override
    public void run() {
        //判断有没有钱
        if (account.money-drawingMoney<0){
            System.out.println(Thread.currentThread().getName()+"钱不够,取不了");
            return;
        }

        try {
            Thread.sleep(1000); //模拟延时
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //卡内余额
        account.money = account.money - drawingMoney;
        //手里的钱
        nowMoney = nowMoney + drawingMoney;

        System.out.println(account.name+"余额为"+account.money);
        //this.getName() = Thread.currentThread().getName() 因为继承了Thread
        System.out.println(this.getName()+"手里的钱"+nowMoney);
    }
}
  • 不安全的集合
import java.util.ArrayList;
import java.util.List;

public class UnsafeList {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < 1000; i++) {
            new Thread(()->{
                list.add(Thread.currentThread().getName());
            }).start();
        }
        System.out.println(list.size());
        //发现不够1000,一瞬间操作多个,覆盖掉了一些线程
    }
}

同步方法

  • 由于我们可以通过private关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是synchronized关键字,它包括两种用法:synchronized方法和synchronized块.
    同步方法: public synchronized void method(int args) {}
    同步块:synchronized (Obj ){ }
  • synchronized方法控制对“对象”的访问,每个对象对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行
    缺陷:若将一个大的方法申明为synchronized将会影响效率
  • 同步块
    synchronized (Obj ){ }
    Obj称之为同步监视器
    ◆ Obj可以是任何对象,但是推荐使用共享资源作为同步监视器
    ◆ 同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this,就是这个对象本身,或者是class [反射中讲解]
    同步监视器的执行过程
  1. 第一个线程访问,锁定同步监视器,执行其中代码
  2. 第二个线程访问,发现同步监视器被锁定,无法访问
  3. 第一个线程访问完毕,解锁同步监视器.
  4. 第二个线程访问,发现同步监视器没有锁,然后锁定并访问
  • 同步后的买票等
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();

        new Thread(station,"小明").start();
        new Thread(station,"老师").start();
        new Thread(station,"黄牛").start();
    }
}

class BuyTicket implements Runnable{

    //票
    private int tickerNums =10;
    boolean flag = true; //外部停止方式

    @Override
    public void run() {
        //买票
        while (flag){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //synchronized同步方法,锁的是this
    private  synchronized void buy() throws InterruptedException {
        //判断是否有票
        if (tickerNums<=0){
            flag = false;
            return;
        }

        //模拟延时
        Thread.sleep(100);

        //买票
        System.out.println(Thread.currentThread().getName()+"拿到票"+tickerNums--);
    }
}
public class UnsafeBank {
    public static void main(String[] args) {
        //账户
        Account account = new Account("peng",100);

        Drawing byPhone = new Drawing(account,50,"peng-1");
        Drawing byBank = new Drawing(account,100,"peng-2");

        byPhone.start();
        byBank.start();
    }
}

//账户
class Account{
    String name;
    int money;

    public Account() {
    }

    public Account(String name, int money) {
        this.name = name;
        this.money = money;
    }
}

//银行:模拟取款
class Drawing extends Thread{

    Account account; //账户
    int drawingMoney; //取多少钱
    int nowMoney; //还有多少钱

    public Drawing(Account account, int drawingMoney, String name) {
        super(name);
        this.account = account;
        this.drawingMoney = drawingMoney;
    }

    //取钱
    //synchronized默认锁的是this
    @Override
    public void run() {
        //account是需要锁的变化的量,即需要增删改的对象
        synchronized (account){
            //判断有没有钱
            if (account.money-drawingMoney<0){
                System.out.println(Thread.currentThread().getName()+"钱不够,取不了");
                return;
            }

            try {
                Thread.sleep(1000); //模拟延时
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //卡内余额
            account.money = account.money - drawingMoney;
            //手里的钱
            nowMoney = nowMoney + drawingMoney;

            System.out.println(account.name+"余额为"+account.money);
            //this.getName() = Thread.currentThread().getName() 因为继承了Thread
            System.out.println(this.getName()+"手里的钱"+nowMoney);
        }
    }
}
import java.util.ArrayList;
import java.util.List;

//不安全的集合
public class UnsafeList {
    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < 1000; i++) {
            new Thread(()->{
                synchronized (list){
                    list.add(Thread.currentThread().getName());
                }
            }).start();
        }

        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(list.size());
        //发现不够1000,一瞬间操作多个,覆盖掉了一些线程
    }
}

CopyOnWriteArray

import java.util.concurrent.CopyOnWriteArrayList;

//测试JUC安全类型的集合
public class TestJUC {
    public static void main(String[] args) {
        CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
        for (int i = 0; i < 1000; i++) {
            new Thread(()->{
                list.add(Thread.currentThread().getName());
            }).start();
        }

        try {
            Thread.sleep(20);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(list.size());
    }
}

死锁

多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行,而导致两个或者多个线程都在等待对方释放资源,都停止执行的情形。某一个同步块同时拥有两个以上对象的锁时,就可能会发生“死锁”的问题

  • 死锁现象
//死锁:多个线程互相抱着对方需要的资源,然后形成僵持
public class DeadLock {
    public static void main(String[] args) {
        Makeup g1 = new Makeup(0,"g1");
        Makeup g2 = new Makeup(1,"g2");

        g1.start();
        g2.start();
    }
}

//口红
class Lipstick{}

//镜子
class Mirror{}

class Makeup extends Thread{

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

    int choice; //选择
    String girlName; //使用化妆品的人

    public 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(2000);
                synchronized (lipstick){ //一秒钟后想获得口红
                    System.out.println(this.girlName+"获得口红的锁");
                }
            }
        }
    }
}

两个线程互相卡住了

解决死锁:自己用完的资源赶紧释放,别拿着这个想着那个

public class DeadLock {
    public static void main(String[] args) {
        Makeup g1 = new Makeup(0,"g1");
        Makeup g2 = new Makeup(1,"g2");

        g1.start();
        g2.start();
    }
}

//口红
class Lipstick{}

//镜子
class Mirror{}

class Makeup extends Thread{

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

    int choice; //选择
    String girlName; //使用化妆品的人

    public 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(2000);
            }
            synchronized (lipstick){ //一秒钟后想获得口红
                System.out.println(this.girlName+"获得口红的锁");
            }
        }
    }
}
  • 产生死锁的四个必要条件(缺一个都锁不上)
  1. 互斥条件:一个资源每次只能被一个进程使用。
  2. 请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放。
  3. 不剥夺条件:进程已获得的资源,在末使用完之前,不能强行剥夺。
  4. 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系。

Lock 锁

  • 显示定义同步锁对象来实现同步
  • java.util.concurrent.locks.Lock接口是控制多个线程对共享资源进行访问的工具。锁提供了对共享资源的独占访问,每次只能有一个线程对Lock对象加锁,线程开始访问共享资源之前应先获得Lock对象
  • ReentrantLock类实现了Lock,它拥有与synchronized相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentrantLock,可以显式加锁、释放锁。
  • 用法
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(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(ticketNums--);
                }else {
                    break;
                }
            } finally {
                lock.unlock();
            }
        }
    }
}
  • synchronized与Lock的对比
    ◆ Lock是显式锁(手动开启和关闭锁,别忘记关闭锁)synchronized是隐式锁,出了作用域自动释放
    ◆ Lock只有代码块锁,synchronized有代码块锁和方法锁
    ◆ 使用Lock锁,JVM将花费较少的时间来调度线程,性能更好。并且具有更好的扩展性(提供更多的子类)
    ◆ 优先使用顺序:Lock > 同步代码块(已经进入了方法体,分配了相应资源) > 同步方法(在方法体之外)

线程通信协作

  • 应用场景:生产者和消费者问题
    ◆ 假设仓库中只能存放一件产品,生产者将生产出来的产品放入仓库,消费者将仓库中产品取走消费
    ◆ 如果仓库中没有产品,则生产者将产品放入仓库,否则停止生产并等待,直到仓库中的产品被消费者取走为止
    ◆ 如果仓库中放有产品,则消费者可以将产品取走消费,否则停止消费并等待,直到仓库中再次放入产品为止
  • 相关Java方法

管程法

//测试生产者和消费者模型-->利用缓冲区:管程法
public class TestPC {
    public static void main(String[] args) {
        SynContainer container = new SynContainer();

        new Productor(container).start();
        new Customer(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+"只鸡");
        }
    }
}

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

    public Customer(SynContainer container) {
        this.container = container;
    }
    
    //消费

    @Override
    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{
    //需要一个容器大小
    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:信号灯法,标志位解决
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;
    }
}

线程池

  • 背景
    经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大。
  • 思路
    提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。
    可以避免频繁创建销毁、实现重复利用。类似生活中的公共交通工具。
  • 好处
    ◆ 提高响应速度(减少了创建新线程的时间)
    ◆ 降低资源消耗(重复利用线程池中线程,不需要每次都创建)
    ◆ 便于线程管理...
    ◆ corePoolSize:核心池的大小
    ◆ maximumPoolSize:最大线程数
    ◆ keepAliveTime:线程没有任务时最多保持多长时间后会终止
  • 相关类
    JDK 5.0起提供了线程池相关API:ExecutorService 和 Executors
  1. ExecutorService:真正的线程池接口。常见子类ThreadPoolExecutor
    ◆ void execute(Runnable command) :执行任务/命令,没有返回值,一般用来执行Runnable
    Future submit(Callable task):执行任务,有返回值,一般又来执行Callable
    ◆ void shutdown():关闭连接池
  2. Executors:工具类、线程池的工厂类,用于创建并返回不同类型的线程池
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());
    }
}
原文地址:https://www.cnblogs.com/peng8098/p/java_01.html