//复制粘贴警告

Java多线程

多线程

线程开启后不一定立即执行,由CPU调度


1. 多线程创建方式


1.1创建线程方式1:继承Thread类,重写run方法线程体,调用start();

/*
   线程开启后不一定立即执行,由cpu安排调度
 */
//创建线程方式1:继承Thread类,重写run方法线程体,调用start();
//继承Thread类
public class TestThread1 extends  Thread{
    //重写run方法线程体
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println("Jay " + i);
        }
    }

    public static void main(String[] args) {
        //创建一个线程对象
        TestThread1 testThread1 = new TestThread1();
        //调用start()方法开启线程
        testThread1.start();
        for (int i = 0; i < 20; i++) {
            System.out.println("Soul " + i);
        }
    }
}

视频链接

package Jay;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

/*
练习Thread,实现多线程同步下载图片
 */
public class TestThread2 extends Thread{
    private String url;
    private String name;
    public TestThread2(String url, String name){
        this.url = url;
        this.name = name;
    }
    //下载图片的线程执行体
    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://cdn.jsdelivr.net/gh/filess/img17@main/2021/05/07/1620371242789-b286c6f7-a06c-48c7-a53b-3a86d18cea97.png", "p1.png");
        TestThread2 t2 = new TestThread2("https://cdn.jsdelivr.net/gh/filess/img16@main/2021/05/07/1620377761880-1d4715d4-482c-4d52-a5aa-210a1a354c77.png", "p2.png");
        TestThread2 t3 = new TestThread2("https://cdn.jsdelivr.net/gh/filess/img8@main/2021/05/07/1620377156603-8b53ee53-8de0-4f81-b667-3df6ce555064.png", "p3.png");

        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 (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常,downloader下载出现问题");
        }
    }
}

视频链接


1.2 创建线程方法2:实现runnable接口,重写run方法执行线程需要丢入runnable接口实现类,调用start方法


//创建线程方法2:实现runnable接口,重写run方法执行线程需要丢入runnable接口实现类,调用start方法
public class TestThread3 implements Runnable{
    //重写run方法线程体
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println("Jay " + i);
        }
    }

    public static void main(String[] args) {
        //创建runnable接口的实现类对象
        TestThread3 testThread3 = new TestThread3();
        //创建线程对象,通过线程对象来开启我的线程(代理)
        new Thread(testThread3).start();
        for (int i = 0; i < 20; i++) {
            System.out.println("Soul " + i);
        }
    }
}

视频链接

多个线程同时操作同一对象,线程不安全,数据紊乱


//多个线程同时操作同一对象,线程不安全,数据紊乱
//买火车票的例子
public class TestThread4 implements Runnable{
    private int ticketNums = 10;

    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();

    }
}

视频链接

龟兔赛跑



import kotlin.reflect.jvm.internal.impl.descriptors.Visibilities;

//模拟龟兔赛跑
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 % 60 == 0)
            {
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            if (gameOver(i)) break;
            System.out.println(Thread.currentThread().getName() + "-->跑了" + i + "步");
        }
    }

    //判断是否完成比赛
    private boolean gameOver (int step){
        if (winner != null){
            return true;
        }
        if (step >= 100) {
            winner = Thread.currentThread().getName();
            System.out.println("Winner is " + winner);
            return true;
        }
        return  false;

    }

    public static void main(String[] args) {
        Race race = new Race();
        new Thread(race, "兔子").start();
        new Thread(race, "乌龟").start();
    }


}

视频链接


1.3 线程创建方式3:实现callable接口


import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
//线程创建方式三:实现callable接口
/*
callable的好处
1、可以定义返回值
2、可以抛出异常
 */
public class TestCallable implements Callable<Boolean> {
    private String url;
    private String name;
    public TestCallable(String url, String name){
        this.url = url;
        this.name = name;
    }
    //下载图片的线程执行体
    public Boolean call(){
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url, name);
        System.out.println(name + " 文件下载成功");
        return true;
    }

    public static void main(String[] args) {
        TestCallable t1 = new TestCallable("https://cdn.jsdelivr.net/gh/filess/img17@main/2021/05/07/1620371242789-b286c6f7-a06c-48c7-a53b-3a86d18cea97.png", "p1.png");
        TestCallable t2 = new TestCallable("https://cdn.jsdelivr.net/gh/filess/img16@main/2021/05/07/1620377761880-1d4715d4-482c-4d52-a5aa-210a1a354c77.png", "p2.png");
        TestCallable t3 = new TestCallable("https://cdn.jsdelivr.net/gh/filess/img8@main/2021/05/07/1620377156603-8b53ee53-8de0-4f81-b667-3df6ce555064.png", "p3.png");

        //创建执行服务:
        ExecutorService ser = Executors.newFixedThreadPool(3);

        //提交执行
        Future<Boolean> r1 = ser.submit(t1);
        Future<Boolean> r2 = ser.submit(t2);
        Future<Boolean> r3 = ser.submit(t3);
        //关闭服务
        ser.shutdownNow();
    }

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

视频链接


2. 静态代理模式

package Jay;
/*
静态代理:
1、真实对象和代理对象都要实现一个接口
2、代理对象需要代理真是角色
 */
public class StaticProxy{
    public static void main(String[] args) {
        new MarryCompany(new you()).happyMarry();
    }
}
interface Marry{
    public void happyMarry();
}

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

//婚庆公司代理
class MarryCompany implements  Marry{
    private Marry target;

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

    @Override
    public void happyMarry() {
        berfore();
        this.target.happyMarry();//这是真实对象
        after();
    }

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

    private void berfore() {
        System.out.println("布置场地");
    }
}

视频链接


3. Lamda表达式


3.1 为什么使用lamda表示

- 避免匿名内部类定义过多
- 使代码看起来简洁,去掉无意义的代码,只留下核心逻辑
- 其实质属于函数式编程的概念

3.2 函数式接口的定义

- 任何接口,如果只包含唯一一个抽象方法,那么它就是一个函数式接口
- 对于函数式接口,我们可以通过lamda表达式来创建接口的对象
package thread.lamda;

/*
推导lamda表达式
 */
public class TestLamda01 {
    //3.静态内部类
    static class Like2 implements ILike{

        @Override
        public void lamda() {
            System.out.println("I like lamda2!");
        }
    }
    public static void main(String[] args) {
        ILike like = new Like();
        like.lamda();

        like = new Like2();
        like.lamda();
        //4.局部内部类
        class Like3 implements ILike{

            @Override
            public void lamda() {
                System.out.println("I like lamda3!");
            }
        }
        like = new Like3();
        like.lamda();
        //5.匿名内部类,没有类的名称,必须借助接口或者父类
        like = new ILike() {
            @Override
            public void lamda() {
                System.out.println("I like lamda4!");
            }
        };
        like.lamda();

        //6.用lamda简化
        like = ()->{
            System.out.println("I like lamda5!");
        };
        like.lamda();
    }
}

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

//2.实现类
class Like implements ILike{

    @Override
    public void lamda() {
        System.out.println("I like lamda!");
    }
}
package thread.lamda;

public class TestLamda02 {
    //静态内部类
    static class love2 implements ILove{
        @Override
        public void love(int a) {
            System.out.println("I love" + a);
        }
    }

    public static void main(String[] args) {
        //普通类实现
        ILove love = new love();
        love.love(1);
        //静态内部类实现
        love = new love2();
        love.love(2);
        //局部内部类
        class love3 implements ILove{
            @Override
            public void love(int a) {
                System.out.println("I love" + a);
            }
        }
        new love3().love(77);
        //匿名内部类
        love = new ILove() {
            @Override
            public void love(int a) {
                System.out.println("I love" + a);
            }
        };
        love.love(3);
        //lamda 简化
        love = (int a)->{
            System.out.println("I love" + a);
        };
        love.love(4);
    }
}

interface ILove{
    void love(int a);
}

class love implements ILove{

    @Override
    public void love(int a) {
        System.out.println("I love" + a);
    }
}

3.3 lamda简化形式

//简化形式1
love = (a) -> {
	System.out.println("I love" + a);
};
//简化形式2(参数<=1)
love = a -> {
	System.out.println("I love" + a);
};
//简化形式3(代码只有一行)
love = a -> System.out.println("I love" + a);

视频链接


4. 线程状态和方法

线程一旦进入死亡状态,就不能再次启动


4.1 五大状态

* 创建状态(new)
* 就绪状态(start)
* 运行状态
* 阻塞状态(sleep,wait)
* 死亡状态

4.2 线程方法

线程方法


4.3 停止线程

- 推荐线程自己停下来(不建议死循环)
- 建议使用一个标志位进行终止变量(当flag= false,则终止线程运行)
- 不要使用stop或者destroy等过时或者JDK不建议使用的方法
package thread.methods;
//测试stop
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){
                testStop.stop();
                System.out.println("线程已经停止");
            }
        }
    }
}

视频链接


4.4 线程休眠(sleep)

* sleep(时间)指定当前线程阻塞的毫秒数
* sleep存在异常InterruptedException
* sleep时间达到后,线程进入就绪状态
* sleep可以模拟网络延时,倒计时等
* 每一个对象都有一个锁,sleep不会释放锁

视频链接


4.5 线程礼让(yield)

package thread.methods;
//测试礼让线程
public class TestYield {
    public static void main(String[] args) {
        //lamda表达式
        Runnable myYield = ()->{
            System.out.println(Thread.currentThread().getName() + "线程开始执行");
            Thread.yield();
            System.out.println(Thread.currentThread().getName() + "线程运行结束");
        };
        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() + "线程运行结束");
//    }
//}

视频链接


4.6 合并线程(Join)

* Join合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞
* 可以想象成插队
package thread.methods;

//测试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 < 500; i++) {
            if (i == 100){
                thread.join();
            }
            System.out.println("main" + i);
        }
    }
}

视频链接


4.7 观测线程状态

package thread.state;

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("/////");
        });
        //观察状态(new)
        Thread.State state = thread.getState();
        System.out.println(state);
        //run
        thread.start();
        state = thread.getState();
        System.out.println(state);

        //只要线程不终止,就一直输出状态
        while (state != Thread.State.TERMINATED){
            Thread.sleep(100);
            state = thread.getState();//更新线程状态
            System.out.println(state);
        }

    }
}

视频链接


5. 线程优先级

优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了,这都是看CPU调度

* 线程的优先级用数字表示,范围从1~10
	* Thread.MIN_PRIORITY = 1
	* Thread.MAX_PRIORITY =10
	* Thread.NORM_PRIORITY = 5
* 使用以下方式改变或者获取优先级
	* getPriority()
	* setPriority(int xxx)
package thread.state;
//测试线程的优先级
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 t6 = new Thread(myPriority);

        t1.setPriority(10);
        t1.start();
        t2.start();
        t3.setPriority(8);
        t3.start();
        t6.setPriority(1);
        t6.start();
    }

}

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

视频链接


6. 守护(daemon)线程

* 线程分为用户线程和守护线程
* 虚拟机必须确保用户线程执行完毕(main)
* 虚拟机不用等待守护线程执行完毕,如后台记录操作日志,监控内存,垃圾回收等待(gc)
package thread.methods;
//测试守护线程
public class TestDaemon {
    public static void main(String[] args) {
        Love love = new Love();
        You you = new You();
        Thread thread = new Thread(love);
        thread.setDaemon(true);//默认是false表示是用户线程
        thread.start();//守护线程启动
        new Thread(you).start();//用户线程启动
    }
}
//守护线程
class Love 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("-====goodbye!world!====-");
    }
}

视频链接


7. 线程同步

并发:同一个对象被多个线程同时操作 形成条件:队列和锁(锁机制synchronized)

* 上万人同时抢100张票
* 两个银行同时取钱

视频链接


7.1 三大不安全案例

package thread.syn;
//不安全的买票
//线程不安全,有负数
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();

        new Thread(buyTicket, "小明").start();
        new Thread(buyTicket, "小红").start();
        new Thread(buyTicket, "小杰").start();
    }
}

class BuyTicket implements Runnable{
    private  int ticketNums = 10;
    boolean  flag = true;
    public void run() {
        while (flag){
            if (ticketNums <= 1) flag = false;
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " 拿到" + ticketNums--);
        }
    }
}
package thread.syn;
//银行取钱
public class UnsafeBank {
    public static void main(String[] args) {
        Account account = new Account(100000, "结婚基金");
        Drawing you = new Drawing(account, 5000, "yourself");
        Drawing yourWife = new Drawing(account, 10000, "yourWife");
        you.start();
        yourWife.start();
    }
}
class Account{
    int money;
    String name;
    public Account(int money, String name) {
        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(this.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);
        //Thread.currentThread().getName() == this.getName();
        System.out.println(this.getName() + "手里的钱为" + nowMoney);
        
   }
}
package thread.syn;
//表格
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 < 100000; i++) {
            new Thread(()->{list.add(Thread.currentThread().getName());}).start();
        }
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(list.size());
    }
}

视频链接


7.2 同步方法

public synchronized void method(int args){} 同步方法的同步监听器就是this,即对象本身,或者是class

package thread.syn;
//安全的买票
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();

        new Thread(buyTicket, "小明").start();
        new Thread(buyTicket, "小红").start();
        new Thread(buyTicket, "小杰").start();
    }
}
class BuyTicket implements Runnable{
    private  int ticketNums = 10;
    boolean  flag = true;
    public void run() {
        while (flag){
            buy();
        }
    }
    //synchronized 同步方法,锁的是this
    private synchronized void buy() {
        if (ticketNums <= 0) {flag = false;return;}
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + " 拿到" + ticketNums--);
    }
}

7.3 同步块

synchronized(Obj){} Obj可以是任何对象,但是推荐使用共享资源(增删改)作为同步监视器

* 同步监视器的执行过程
	* 第一个线程访问,锁定同步监视器,执行其中代码。
	* 第二个线程访问,发现同步监视器被锁定,无法访问
	* 第一个线程访问完毕,解锁同步监视器
	* 第二线程访问,发现同步监视器没有锁,然后锁定并访问
package thread.syn;

public class UnsafeBank {
    public static void main(String[] args) {
        Account account = new Account(100000, "结婚基金");
        Drawing you = new Drawing(account, 5000, "yourself");
        Drawing yourWife = new Drawing(account, 10000, "yourWife");
        you.start();
        yourWife.start();
    }
}
class Account{
    int money;
    String name;
    public Account(int money, String name) {
        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() {
        synchronized (account){
            if (account.money - drawingMoney < 0){
                System.out.println(this.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);
            //Thread.currentThread().getName() == this.getName();
            System.out.println(this.getName() + "手里的钱为" + nowMoney);
        }
    }
}
package thread.syn;

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 < 100000; 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());
    }
}

视频链接

CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>(); 自带锁的list

package thread.syn;

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 < 10000; i++) {
            new Thread(()-> list.add(Thread.currentThread().getName())).start();
        }
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(list.size());

    }
}

视频链接


7.4 死锁

死锁:某一个同步块同时拥有“两个以上对象的锁”

package thread.syn;
//死锁:多个线程互相抱着对方需要的资源,然后形成僵持
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 name;//使用化妆品的人
    MakeUp(int choice, String name) {
        this.choice = choice;
        this.name = name;
    }
    @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.name + "获得口红");
                Thread.sleep(1000);
            }
            synchronized (mirror) {//获得镜子的锁
                System.out.println(this.name + "获得镜子的锁");
            }
        } else {
            synchronized (mirror) {//获得镜子的锁
                System.out.println(this.name + "获得镜子的锁");
                Thread.sleep(2000);
                }
            synchronized (lipStick) {//获得口红的锁
                System.out.println(this.name + "获得口红的锁");
            }
        }
    }
}

视频链接


7.5 锁(显性LOCK)

package thread.syn;
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{
    private int tickNums = 10;
    boolean flag = true;
    private final ReentrantLock reentrantLock = new ReentrantLock();
    @Override
    public void run() {
        try{
            reentrantLock.lock();
            while (flag){
                if (tickNums <= 0 ){
                    flag = false;
                    return;
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "获得了" + tickNums--);
            }
        }finally {
            reentrantLock.unlock();
        }
    }
}

视频链接


8. 线程协作

生产者消费者问题:生产者和消费者共享同一个资源,并且生产者和消费者之间相互依赖,互为条件

作用 方法名
表示线程一直等待,直到其他线程通知,与sleep不同,会释放锁 wait()
指定等待的毫秒数 wait(long timeout)
唤醒一个等待状态的线程 notify()
唤醒同一个对象上所有调用wait()方法的线程,优先级别高的线程优先调度 notifyAll()

8.1 解决方式1

并发协作模型“生产者/消费者模式”-->管程法

* 生产者:负责生产数据的模块(可能是方法,对象,线程,进程)
* 消费者:负责处理数据的模块(可能是方法,对象,线程,进程)
* 缓冲区:消费者不能直接使用生产者的数据,他们之间有个“缓冲区”

生产者将生产好的数据放入缓冲区,消费者从缓冲区拿出数据
视频链接

package thread.itc;
//测试:生产者消费者模型-->管程法
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 = 1; i < 100; i++) {
            container.push(new Chicken(i));
            System.out.println("生产了" + i + "只鸡");
            try {
                Thread.sleep(0);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
//消费者
class Consumer extends Thread{
    SynContainer container;
    public Consumer(SynContainer container){
        this.container = container;
    }
    //消费
    @Override
    public void run() {
        for (int i = 1; i < 100; i++) {
            System.out.println("消费了-->" + container.pop().id + "只鸡");
            try {
                Thread.sleep(0);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
//产品
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;
    }
}

视频链接


8.2 解决方式2

并发协作模型“生产者/消费者模式”-->信号灯法

package thread.itc;
////测试:生产者消费者模型-->信号灯法
public class TestPC2 {
    public static void main(String[] args) {
        Program program = new Program();
        new Player(program).start();
        new Audience(program).start();
    }
}
//生产者-->演员
class Player extends Thread{
    Program program;
    public Player(Program program){
        this.program = program;
    }
    @Override
    public void run() {
        for (int i = 1; i < 20; i++) {
            this.program.show ("Jay's专场", i);
        }
    }
}
//消费者-->观众
class Audience extends Thread{
    Program program;
    public Audience(Program program){
        this.program = program;
    }
    @Override
    public void run() {
        for (int i = 1; i < 20; i++) {
            this.program.clap();
        }
    }
}
//产品-->节目
class Program{
    //演员表演,观众观看 T
    //观众鼓掌,演员致敬 F
    String name;//表演的节目
    int order;//节目序号
    boolean  flag = true;//信号灯
    //表演
    public synchronized void show (String name, int order){
        if(!flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("演员表演了" + name + "第" + order + "个节目");
        //观众鼓掌喝彩,演员致敬
        this.notifyAll();
        this.name = name;
        this.order = order;
        this.flag = !this.flag;
    }
    //鼓掌
    public synchronized void clap(){
        if (flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("观众看完" + name + "第" + order + "个节目,会场响起热烈掌声,演员们鞠躬致敬");
        this.notifyAll();
        this.flag = !this.flag;
    }
}

视频链接


9. 线程池

* 背景:经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大
* 思路:提前创建好多个线程,放到线程池中,使用时直接获取,使用完放回池中。可以避免繁创建销毁、实现重复利用。类似生活中的公共交通工具(单车)。
* 好处:
	* 提高响应速度(减少了创建新线程的时间)
	* 降低资源消耗(重复利用线程池中线程,不用每次都创建)
	* 便于线程管理

newFixedThreadPool:线程池大小
corePoolSize:核心池的大小
maximumPoolSize:最大线程数
keepAliveTime:线程没有任务时最多保持多长时间后会终止
线程池相关API:ExecutorService 和 Executors
void execute(Runnable command):执行任务/命令,没有返回值,一般用来执行Runnable
<T>Future<T>submit(Callable<T>task):执行任务,有返回值,一般用来执行
Callablevoid shutdown():关闭连接池
Executors:工具类、线程池的工厂类,用于创建并返回不同类型的线程池

package thread.syn;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

//测试线程池
public class TestPool {
    public static void main(String[] args) {
        //1.创建线程池
        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() {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName() + "  " + i);
        }
    }
}

视频链接1
视频链接2


posted @ 2021-07-22 19:58  Jezer  阅读(156)  评论(0)    收藏  举报