多线程详解

1 线程简介

多任务→多线程

进程 VS 线程

  • 程序是指令和数据的有序集合,是一个静态的概念。
  • 进程是程序的一次执行过程,是一个动态的概念。
  • 进程中至少有一个线程,线程是CPU调度和执行的基本单位。

2 线程创建

三种创建方式:

  1. 继承Thread类
  2. 实现Runnable接口
  3. 实现Callable接口(了解)

2.1 继承Thread类

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

//注意,线程开启不一定立即执行,由CPU调度执行
public class TestThread1 extends Thread{
    @Override
    public void run() {
        // run方法线程体
        for(int i = 0;i < 20;i++) {
            System.out.println("我在看代码—————"+i);
        }
    }
    public static void main(String[] args) {
        //main线程,主线程
        TestThread1 testThread1 = new TestThread1();
        //调用start()方法开启线程,交替执行
        testThread1.start();
        for(int i = 0;i < 20;i++) {
            System.out.println("我在学习多线程—————"+i);
        }
    }    
}

实现多线程同步下载图片

import java.io.File;
import java.net.URL;
import org.apache.commons.io.FileUtils;
public class TestThread2 extends Thread{
    private String url,name; //网络图片地址,保存的文件名
    public TestThread2(String url,String name) {
        this.url = url;
        this.name = name;
    }
    //下载图片线程执行体
    @Override
    public void run() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url, name);
        System.out.println("下载了文件名为:"+name);
    }

    public static void main(String[] args) {
        TestThread2 t1 = new TestThread2("https://pics6.baidu.com/feed/838ba61ea8d3fd1ffe50b135beb0651894ca5f6d.jpeg?token=34d0744ffdbbc1f2d6ddea302862b052","1.jpg");
        TestThread2 t2 = new TestThread2("https://pics6.baidu.com/feed/838ba61ea8d3fd1ffe50b135beb0651894ca5f6d.jpeg?token=34d0744ffdbbc1f2d6ddea302862b052","2.jpg");
        TestThread2 t3 = new TestThread2("https://pics6.baidu.com/feed/838ba61ea8d3fd1ffe50b135beb0651894ca5f6d.jpeg?token=34d0744ffdbbc1f2d6ddea302862b052","3.jpg");
        t1.start();
        t2.start();
        t3.start();
    }
}
 //下载器
class WebDownloader{
    //下载方法
    public void downloader(String url,String name) {
        try {
            FileUtils.copyURLToFile(new URL(url), new File(name));
        }catch (Exception e) {
            e.printStackTrace();
            System.out.println("IO异常,downloader方法出现问题");
        }
    }
}

2.2 实现Runnable接口

创建线程方式二:实现Runnable接口→重写run()方法→调用start()启动线程(需要Runnable接口实现类)

public class TestThread3 implements Runnable{
    @Override
    public void run() {
        // run方法线程体
        for(int i = 0;i < 20;i++) {
            System.out.println("我在看代码—————"+i);
        }
    }
    public static void main(String[] args) {
        //创建runnable接口的实现类对象
        TestThread3 testThread3 = new TestThread3();
        
        //创建线程对象,通过线程对象来开启线程,代理
//        Thread thread = new Thread(testThread3);
//        thread.start();
        new Thread(testThread3).start();
        
        for(int i = 0;i < 20;i++) {
            System.out.println("我在学习多线程—————"+i);
        }
    }
}
import java.io.File;
import java.net.URL;
import org.apache.commons.io.FileUtils;
//练习Thread,实现多线程同步下载图片
public class TestThread2n implements Runnable{
    private String url,name; //网络图片地址,保存的文件名
    public TestThread2n(String url,String name) {
        this.url = url;
        this.name = name;
    }
    //下载图片线程执行体
    @Override
    public void run() {
        WebDownloader1 webDownloader = new WebDownloader1();
        webDownloader.downloader(url, name);
        System.out.println("下载了文件名为:"+name);
    }

    public static void main(String[] args) {
        TestThread2n t1 = new TestThread2n("https://pics6.baidu.com/feed/838ba61ea8d3fd1ffe50b135beb0651894ca5f6d.jpeg?token=34d0744ffdbbc1f2d6ddea302862b052","1.jpg");
        TestThread2n t2 = new TestThread2n("https://pics6.baidu.com/feed/838ba61ea8d3fd1ffe50b135beb0651894ca5f6d.jpeg?token=34d0744ffdbbc1f2d6ddea302862b052","2.jpg");
        TestThread2n t3 = new TestThread2n("https://pics6.baidu.com/feed/838ba61ea8d3fd1ffe50b135beb0651894ca5f6d.jpeg?token=34d0744ffdbbc1f2d6ddea302862b052","3.jpg");
        
        new Thread(t1).start();
        new Thread(t2).start();
        new Thread(t3).start();
    }

}
//下载器
class WebDownloader1{
    //下载方法
    public void downloader(String url,String name) {
        try {
            FileUtils.copyURLToFile(new URL(url), new File(name));
        }catch (Exception e) {
            e.printStackTrace();
            System.out.println("IO异常,downloader方法出现问题");
        }
    }
}

小结:

  • 继承Thread类

    • 子类继承Thread类具备多线程能力
    • 启动线程:子类对象.start()
    • 不建议使用:避免OOP单继承局限性
  • 实现Runnable接口

    • 实现接口Runnable具有多线程能力
    • 启动线程:传入目标对象+Thread对象.start()
    • 推荐使用:避免单继承局限性,灵活方便,方便同一对象被多个线程使用

多个线程同时操作一个对象,买火车票的例子

//问题:多个线程操作同一个资源,线程不安全,数据紊乱
public class TestThread4 implements Runnable{
    //票数
    private int ticketNum = 10;
    @Override
    public void run() {
        while(true) {
            if(ticketNum<=0) {
                break;
            }
            try {
                Thread.sleep(10);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNum--+"张票");
        }    
    }
    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; 
    public static void main(String[] args) {
        Race race = new Race();
        new Thread(race,"兔子").start();
        new Thread(race,"乌龟").start();
    }
    @Override
    public void run() {
        for(int i = 0; i <= 100;i++) {
            //模拟兔子休息
            if("兔子".equals(Thread.currentThread().getName() )&& i%10==5) {
                try {
                    Thread.sleep(56);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if("乌龟".equals(Thread.currentThread().getName() )) {
                try {
                    Thread.sleep(5);
                } 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;
        }else {
            if(steps==100) {
                winner = Thread.currentThread().getName();
                System.out.println("winner is "+winner);
                return true;
            }
        }
        return false;
    }
}

2.3 实现Callable接口

创建线程方式三(了解即可):实现Callable接口(需要返回值类型)→重写call()方法(需要抛出异常)→创建目标对象→创建关闭服务

import java.io.File;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.commons.io.FileUtils;

//创建方式三:实现Callable接口
/*
 * Callable的好处:
 * 1.可以定义返回值
 * 2.可以抛出异常
 */
public class TestCallable implements Callable{
    private String url,name; //网络图片地址,保存的文件名
    public TestCallable(String url,String name) {
        this.url = url;
        this.name = name;
    }
    //下载图片线程执行体
    @Override
    public Boolean call() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url, name);
        System.out.println("下载了文件名为:"+name);
        return true;
    }

    public static void main(String[] args) throws Exception {
        TestCallable t1 = new TestCallable("https://pics6.baidu.com/feed/838ba61ea8d3fd1ffe50b135beb0651894ca5f6d.jpeg?token=34d0744ffdbbc1f2d6ddea302862b052","1.jpg");
        TestCallable t2 = new TestCallable("https://pics6.baidu.com/feed/838ba61ea8d3fd1ffe50b135beb0651894ca5f6d.jpeg?token=34d0744ffdbbc1f2d6ddea302862b052","2.jpg");
        TestCallable t3 = new TestCallable("https://pics6.baidu.com/feed/838ba61ea8d3fd1ffe50b135beb0651894ca5f6d.jpeg?token=34d0744ffdbbc1f2d6ddea302862b052","3.jpg");
        
        //创建执行服务 
        ExecutorService ser = Executors.newFixedThreadPool(3);
        
        //提交执行
        Future r1 = ser.submit(t1);
        Future r2 = ser.submit(t2);
        Future r3 = ser.submit(t3);
        
        //获取结果
        boolean rs1 = r1.get();
        boolean rs2 = r2.get();
        boolean rs3 = r3.get();
        
        System.out.println(rs1);
        System.out.println(rs2);
        System.out.println(rs3);
        //关闭服务
        ser.shutdown();
    }
}
 //下载器
class WebDownloader{
    //下载方法
    public void downloader(String url,String name) {
        try {
            FileUtils.copyURLToFile(new URL(url), new File(name));
        }catch (Exception e) {
            e.printStackTrace();
            System.out.println("IO异常,downloader方法出现问题");
        }
    }
}

Lamda表达式

语法:(parameters) -> expression 或 (parameters) ->{ statements; }

作用:简化代码,避免匿名内部类定义过多

Function Interface(函数式接口):只包含唯一一个抽象方法

可以通过lamda表达式来创建函数式接口的对象

推导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();
    }
}
//1.定义一个函数式接口
interface ILike{
    void lambda();
}
//2.实现类
class Like implements ILike{
    @Override
    public void lambda() {
        System.out.println("I like lambda");
    }    
}

简化lambda表达式:1.省略参数类型 2.省略括号

静态代理

示例(婚庆公司)

public class StaticProxy {

    public static void main(String[] args) {
        You you = new You(); 
        you.HappyMarry();
        //        new Thread(()->System.out.println("我爱你")).start();
//        new WeddingCompany(new You()).HappyMarry();
        //代理
        WeddingCompany weddingCompany = new WeddingCompany(new 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("结婚之前,布置现场");        
    }    
}

静态代理模式总结:

  • 真实对象和代理对象都要实现同一个接口
  • 代理对象代理真实对象

好处:

  • 代理对象可以做很多真实对象做不了的事情
  • 真实对象专注做自己的事情

3 线程状态

3.1 五大状态

多线程详解_第1张图片

多线程详解_第2张图片

3.2 线程停止

  • 不推荐使用JDK提供的stop()、destroy()方法【已废弃】
  • 推荐线程自己停下来(建议使用一标志位进行终止变量)
//测试stop
//1.建议线程正常停止-->利用次数,不建议死循环
//2.建议使用标志位
//3.不要使用stop或者destroy等过时或者JDK不建议使用的方法
public class TestStop implements Runnable{
    private boolean flag = true;
    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("线程停止");
            }
        }
    }
    @Override
    public void run() {
        int i = 0;
        while(flag) {
            System.out.println("run ... Thread"+i++);
        }    
    }
    public void stop() {
        this.flag = false;
    }
}

3.3 线程休眠

sleep(毫秒)→就绪

每个对象有个锁,sleep不会释放锁

//模拟网络延时:放大问题的发生性
public class TestSleep implements Runnable{
    //票数
    private int ticketNum = 10;
    @Override
    public void run() {
        while(true) {
            if(ticketNum<=0) {
                break;
            }
            //模拟延时
            try {
                Thread.sleep(100);
            } catch (Exception e) {
                e.printStackTrace();
            }            System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNum--+"张票");
        }    
    }
    public static void main(String[] args) {
        TestSleep ticket = new TestSleep();
        new Thread(ticket,"小明").start();
        new Thread(ticket,"老师").start();
        new Thread(ticket,"黄牛党").start();
    }
}
import java.text.SimpleDateFormat;
import java.util.Date;

public class TestSleep2{
    public static void main(String[] args) {
        //模拟倒计时
        try {
            tenDown();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();            
        }
        //打印当前系统时间
        Date startTime = new Date(System.currentTimeMillis());
        while(true) {
            try {
                System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
                Thread.sleep(1000);
                startTime = new Date(System.currentTimeMillis()); //更新当前时间
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }        
    }
    public static void tenDown() throws InterruptedException {
        int num = 3;
        while(true) {
            Thread.sleep(1000);
            System.out.println(num--);
            if(num<=0) {
                break;
            }
        }    
    }
}

3.4 线程礼让

Yield让当前线程暂停但不阻塞,转为就绪状态

礼让不一定成功

//测试礼让线程,礼让不一定成功
public class TestYield {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        MyYield myYield = new MyYield();
        new Thread(myYield,"a").start();
        new Thread(myYield,"b").start();
    }
}
class MyYield implements Runnable{
    @Override
    public void run() {
        // TODO Auto-generated method stub
        System.out.println(Thread.currentThread().getName()+"线程开始执行");
        Thread.yield(); //礼让
        System.out.println(Thread.currentThread().getName()+"线程停止执行");
    }    
}

3.5 线程强制执行

Join合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞(可以看作是插队)

//测试join方法
public class TestJoin implements Runnable{
    public static void main(String[] args) throws InterruptedException {
        //启动我们的线程
        TestJoin testJoin = new TestJoin();
        Thread thread = new Thread(testJoin);
        thread.start();
        for (int i = 0; i < 500; i++) {
            if(i==200) {
                thread.join();//插队
            }
            System.out.println("main"+i);
        }
    }
    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println("线程vip来了"+i);
        }    
    }
}

3.6 线程优先级

优先高的不一定先执行,默认是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);
        //先设置优先级,再启动
        t1.start();
        t2.setPriority(1);
        t2.start();
        t3.setPriority(4);
        t3.start();
        t4.setPriority(Thread.MAX_PRIORITY); //MAX_PRIORITY=10
        t4.start();
    }

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

3.7 守护(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 < 36500; i++) {
            System.out.println("开心活着");
        }
        System.out.println("====Good bye!====");
    }    
}

4 线程同步

多个线程操作同一资源(并发)

线程同步是一种等待机制,多个需要同时访问同一对象的线程进图该对象的等待池形成队列,等待前面线程使用完毕,下一线程再使用

形成条件:队列+锁(synchronized)

4.1 同步方法及同步块

三个不安全案例

1.不安全的买票

//不安全的买票(线程不安全)
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 ticketNum = 10;
    boolean flag = true; //外部停止方式
    @Override
    public void run() {
        //买票
        while(flag) {
            buy();
        }
    }
    private void buy() {
        if(ticketNum<=0) {
            flag = false;
            return;
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //买票
        System.out.println(Thread.currentThread().getName()+"拿到"+ticketNum--);
    }
    
}

2.不安全的取钱

//不安全的取钱(两个人)
public class UnsafeBank {
    public static void main(String[] args) {
        Account account = new Account(100,"结婚基金");
        Drawing you = new Drawing(account,50,"你");
        Drawing GF = new Drawing(account,100,"女朋友");
        you.start();
        GF.start();
    }

}
//账户
class Account{
    int money; //余额
    String name; //卡名
    public Account(int money, String name) {
        super();
        this.money = money;
        this.name = name;
    }
}
//银行:模拟取款
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(100);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //卡内余额 = 余额 - 取的钱
        account.money = account.money - drawingMoney;
        //你手里的钱
        nowMoney = nowMoney + drawingMoney;
        System.out.println(account.name+"余额为:"+account.money);
        //Thread.currentThread() == this.getName()
        System.out.println(this.getName()+"手里的钱:"+nowMoney);
    }
}

3.不安全的集合

//线程不安全的集合
//添加到同一位置被覆盖
public class UnsafeList {
    public static void main(String[] args) {
        List list = new ArrayList();
        for (int i = 0; i < 10000; i++) {
            new Thread(()->{
                list.add(Thread.currentThread().getName());
            }).start();
        }
        System.out.println(list.size());
    }
}

synchronized

同步方法:public synchronized void method(int args) { }

synchronized方法控制对“对象”的访问,每个对象对象对应一把锁,每个synchronized方法都必须获得调用该方法的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行

同步块:synchronized(Obj) { }

Obj称为同步监视器

  • Obj可以是任何对象,但是推荐使用共享资源作为同步监视器
  • 同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this
public void run() {
        //锁的对象就是变化的量,需要增删改的对象
        synchronized (account) {
            //判断有没有钱
            if(account.money - drawingMoney < 0) {
                System.out.println(Thread.currentThread().getName()+"钱不够,取不了");
                return;
            }
            //放大问题的发生性
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //卡内余额 = 余额 - 取的钱
            account.money = account.money - drawingMoney;
        }
        //你手里的钱
        nowMoney = nowMoney + drawingMoney;
        System.out.println(account.name+"余额为:"+account.money);
        //Thread.currentThread() == this.getName()
        System.out.println(this.getName()+"手里的钱:"+nowMoney);
    }

CopyOnWriteArrayList

JUC就是java.util .concurrent工具包的简称。这是一个处理线程的工具包,JDK 1.5开始出现的。Callable接口也在JUC中。

import java.util.concurrent.CopyOnWriteArrayList;

//测试JUC安全类型的集合
public class TestJUC {
    public static void main(String[] args) {
        CopyOnWriteArrayList list = new CopyOnWriteArrayList();
        for(int i = 0; i < 10000; i++) {
            new Thread(()->{
                list.add(Thread.currentThread().getName());
            }).start();
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(list.size());
    }
}

4.2 死锁

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

//死锁:多个线程互相抱着对方需要的资源,然后形成僵持
public class DeadLock {

    public static void main(String[] args) {
        Makeup g1 = new Makeup(0,"灰姑娘");
        Makeup g2 = new Makeup(1,"白雪公主");
        g1.start();
        g2.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) {
            // TODO Auto-generated catch block
            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+"获得口红的锁");
                }
            }
        }
    }
}

锁中锁(多个对象互相嵌套的锁)使多个线程互相抱着对方需要的资源,然后形成僵持

解决方法:锁分开写,不要同时占有多个资源

//化妆,互相持有对方的锁,就是需要拿到对方的资源
    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. 循环等待条件

4.3 Lock锁

从JDK 5.0开始,Java提供了更强大的线程同步机制——显式定义同步锁对象来实现同步。同步锁使用Lock对象充当,Lock锁也包含在JUC内

ReentrantLock(可重入锁)类实现了Lock,可以显式加锁、释放锁

使用格式:

Lock lock=new ReentrantLock();
lock.lock();
try{
    //处理任务
}catch(Exception ex){
     
}finally{
    lock.unlock();   //释放锁
}

测试Lock类(买票):

import java.util.concurrent.locks.ReentrantLock;

//测试Lock类
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 ticketNum = 10;
    
    //定义Lock锁
    private final ReentrantLock lock = new ReentrantLock();
    @Override
    public void run() {
        while(true) {
            lock.lock();//加锁
            try {
                if(ticketNum > 0) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println(ticketNum--);
                }else {
                    break;
                }
            }finally {
                //解锁
                lock.unlock();
            }        
        }
    }
}

synchronized与Lock对比

  • Lock是显式锁(手动开启和关闭锁),synchronized是隐式锁,自动释放
  • 使用Lock锁,JVM将花费较少的时间来调度线程,性能更好。并且具有更好的扩展性(提供更多子类)

4.4 线程通信

线程通信方法:

多线程详解_第3张图片

注意:均是Object类的方法,都只能在同步方法或者同步代码块中使用,否则会抛出异常

生产者消费者问题

解决方法:

  1. 利用缓冲区解决:管程法

    //测试生产者消费者模型-->利用缓冲区解决:管程法
    
    //生产者,消费者,产品,缓冲区
    public class TestPC {
        public static void main(String[] args) {
            SynContainer container = new SynContainer();        
            new Producer(container).start();
            new Consumer(container).start();
        }
    
    }
    
    //生产者
    class Producer extends Thread{
        SynContainer container;
        public Producer(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 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+"只鸡");
                }        
            }
    }
    
    //产品
    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) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            //如果没有满,我们就需要丢入产品
            chickens[count] = chicken;
            count++;
            
            //可以通知消费者消费了
            this.notifyAll();
        }
    
        //消费者消费产品
        public synchronized Chicken pop() {
            //判断能否消费
            if(count==0) {
                //等待生产者生产
                try {
                    this.wait();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            //如果可以消费
            count--;
            Chicken chicken = chickens[count];    
            //吃完了,通知生产者生产
            this.notifyAll();
            return chicken;
            
        }
    }
  2. 利用标志位解决:信号灯法

    package com.zhg.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) {
                    // TODO Auto-generated catch block
                    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) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            System.out.println("观众观看了:"+voice);
            //通知演员表演
            this.notifyAll();
            this.flag = !this.flag;
        }
    }

线程池

背景:经常创建和销毁,使用量特别大的资源,比如并发情况下的线程,对性能影响很大。

思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回池中。可以避免频繁创建销毁、实现重复利用。

好处:

  • 提高响应速度
  • 降低资源消耗
  • 便于线程管理

JDK 5.0起提供了线程池相关API:ExecutorService和Executors

  • ExecutorService:真正的线程池接口。
  • Executor:工具类、线程池的工厂类,用于创建并返回不同类型的线程池。
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());
        
    }
}

你可能感兴趣的