shanX
文章31
标签17
分类9
JAVA-线程

JAVA-线程

线程

线程创建

Thread、Runnable、Callable

继承 Thread 类实现 Runnable 接口 为重点,实现 Callable 接口仅作了解

Thread

  1. 自定义线程类继承 Thread 类
  2. 重写 run()方法,编写线程执行体
  3. 创建线程对象,调用 start()方法启动线程
// 创建线程的方式:继承Thread类 、重写run()方法、 调用start开启线程

// 总结:线程开启不一定立即执行,由cpu进行调度执行

public class TestThread01 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主线程
        // 创建一个线程对象
        TestThread01 testThread01 = new TestThread01();
        //调用start()方法开启线程
        testThread01.start();

        for (int i = 0; i < 2000; i++) {
            System.out.println("正在执行主方法******" + i);
        }
    }
}

实现多线程同步下载图片(commons-io)

/**
 * 实现多线程同步下载图片
 */
public class TestThread2 extends Thread {
    private String url;
    private String 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://pics2.baidu.com/feed/902397dda144ad348afc39466dd25efc30ad852d.jpeg?token=4f48564797f3e5ddda4bb40071f78be5", "t1.jpg");
        TestThread2 t2 = new TestThread2
                ("https://pics2.baidu.com/feed/902397dda144ad348afc39466dd25efc30ad852d.jpeg?token=4f48564797f3e5ddda4bb40071f78be5", "t2.jpg");
        TestThread2 t3 = new TestThread2
                ("https://pics2.baidu.com/feed/902397dda144ad348afc39466dd25efc30ad852d.jpeg?token=4f48564797f3e5ddda4bb40071f78be5", "t3.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 (IOException e) {
            e.printStackTrace();
            System.out.println("io异常,downloader方法出现问题");
        }
    }
}

实现 Runable 接口

  1. 定义 MyRunnable 类实现 Runnable 接口
  2. 实现 run()方法,编写线程执行体
  3. 创建线程对象,调用 start()方法启动线程
public class TestRunable01 implements Runnable {
    //run方法线程体
    @Override
    public void run() {
        for (int i = 0; i < 200; i++) {
            System.out.println("我在看代码--" + i);
        }
    }

    //执行下面代码
    public static void main(String[] args) {
        //main线程,主线程
        //创建一个Runable接口的实现对象
        TestRunable01 testRunable01 = new TestRunable01();

        //创建线程对象,通过线程对象来开启线程,这种方式叫做代理
        new Thread(testRunable01).start();

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

Runable-实现多线程同步下载图片(commons-io)

package com.thread.demo01;

import org.apache.commons.io.FileUtils;

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

/**
 * 实现多线程同步下载图片
 */
public class TestRunable02 extends Thread {
    private String url;
    private String name;

    public TestRunable02(String url, String name) {
        this.url = url;
        this.name = name;
    }


    @Override
    public void run() {
        WebDownLoader2 webDownLoader = new WebDownLoader2();
        webDownLoader.downloader(url,name);
        System.out.println("下载文件名为:" + name);

    }

    public static void main(String[] args) {
        TestThread2 t1 = new TestThread2
                ("https://pics2.baidu.com/feed/902397dda144ad348afc39466dd25efc30ad852d.jpeg?token=4f48564797f3e5ddda4bb40071f78be5", "t1.jpg");
        TestThread2 t2 = new TestThread2
                ("https://pics2.baidu.com/feed/902397dda144ad348afc39466dd25efc30ad852d.jpeg?token=4f48564797f3e5ddda4bb40071f78be5", "t2.jpg");
        TestThread2 t3 = new TestThread2
                ("https://pics2.baidu.com/feed/902397dda144ad348afc39466dd25efc30ad852d.jpeg?token=4f48564797f3e5ddda4bb40071f78be5", "t3.jpg");
        new Thread(t1).start();
        new Thread(t2).start();
        new Thread(t3).start();
    }

}

//下载器
class WebDownLoader2 {
    //下载方法
    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方法出现问题");
        }
    }
}

Thread 与 Runable 比较

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

买火车票的例子

存在并发问题,会出现多个不同用户抢到同一张票的问题;

package com.thread.demo01;

/**
 * 多个县城同时操作一个对象
 * 买火车票的例子
 */
public class TestThread03 implements Runnable {
    //票数
    private static int ticketNum = 10;

    @Override
    public void run() {
        while (true) {
            if (ticketNum<=0){
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "------拿到了第" + ticketNum-- + "张票------");
        }
    }

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

        new Thread(ticket, "小明").start();
        new Thread(ticket, "小二").start();
        new Thread(ticket, "阿黄").start();
    }
}
小明------拿到了第10张票------
阿黄------拿到了第9张票------
小二------拿到了第8张票------
小明------拿到了第7张票------
小二------拿到了第7张票------
阿黄------拿到了第7张票------
阿黄------拿到了第6张票------
小二------拿到了第6张票------
小明------拿到了第5张票------
小明------拿到了第3张票------
小二------拿到了第4张票------
阿黄------拿到了第4张票------
阿黄------拿到了第2张票------
小二------拿到了第2张票------
小明------拿到了第2张票------
阿黄------拿到了第0张票------
小二------拿到了第-1张票------
小明------拿到了第1张票------

模拟龟兔赛跑

/**
 * 模拟龟兔赛跑
 */
public class Race implements Runnable {
    private static String winner;

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

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

            //判断比赛是否结束
            boolean flag = gameOver(i);
            //出现winner,跳出
            if (flag) {
                break;
            }

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

    //判断是否完成比赛
    public 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;
    }

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

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

    }
}

实现 Callable 接口(仅了解) 扩充

  1. 实现 Callable 接口,需要返回值类型
  2. 重写 call 方法,需要抛出异常
  3. 创建目标对象
  4. (1)创建执行服务 ExecutorService ser=Executors.newFixedThreadPool(3); //线程池,并发数
  5. (2)提交执行 Future<Boolean> result = ser.submit(t1);
  6. (3)获取结果 boolean r1 = result.get();
  7. (4)关闭服务 ser.shutdownNow();

示例代码如下:

import java.util.concurrent.*;

public class TestCallable implements Callable {
    private String url;
    private String name;

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

    @Override
    public Object call() throws Exception {
        WebDownLoader wd = new WebDownLoader();
        wd.downloader(url,name);
        System.out.println("下载文件,名为---" + name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable t1 = new TestCallable
                ("https://pics2.baidu.com/feed/902397dda144ad348afc39466dd25efc30ad852d.jpeg?token=4f48564797f3e5ddda4bb40071f78be5", "t1.jpg");
        TestCallable t2 = new TestCallable
                ("https://pics2.baidu.com/feed/902397dda144ad348afc39466dd25efc30ad852d.jpeg?token=4f48564797f3e5ddda4bb40071f78be5", "t2.jpg");
        TestCallable t3 = new TestCallable
                ("https://pics2.baidu.com/feed/902397dda144ad348afc39466dd25efc30ad852d.jpeg?token=4f48564797f3e5ddda4bb40071f78be5", "t3.jpg");

        //1.创建执行服务
        ExecutorService serv = Executors.newFixedThreadPool(3); //线程池,并发数

        //2.提交执行
        Future<Boolean> r1 = serv.submit(t1);
        Future<Boolean> r2 = serv.submit(t2);
        Future<Boolean> r3 = serv.submit(t3);
        //3.获取结果
        boolean rs1 = r1.get();
        boolean rs2 = r2.get();
        boolean rs3 = r3.get();

        System.out.println(rs1);
        System.out.println(rs2);
        System.out.println(rs3);

        //4.关闭服务
        serv.shutdownNow();
    }
}

静态代理–个人结婚与婚庆公司的例子

package com.thread.demo01;
// 静态代理模式:
// 真实对象和代理对象都要实现同一个接口
// 代理对象要代理真实角色

// 好处 :
// 1. 代理对象可以做很多真实对象做不了的事情
// 2. 真实对象专注做自己的事情

public class StaticProxy {

    public static void main(String[] args) {

        You you = new You(); // 真实对象
        new Thread(() -> System.out.println("i love you")).start(); // lambda表达式

//        //传统调用方式
//        You you = new You();
//        you.HappyMarry();

        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("结婚,超开心(^_^)"); //no-qinjiang
    }
}

//代理角色,帮助你结婚, 起到帮助作用
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 before() {
        System.out.println("布置婚礼现场");
    }

    private void after() {
        System.out.println("还债结尾款");
    }
}

Lambda 表达式

为什么要使用 lambda 表达式

  1. 避免匿名内部类定义过多

  2. 可以让代码看起来更简洁

  3. 去掉无意义代码,留下核心逻辑

    注:只有一行代码的情况下才能简化成一行;前提是接口为函数式接口

理解函数式接口(Functional Interface)是学习 java8 lambda 表达式的关键所在

函数式接口的定义:

任何接口,如果只包含一个抽象方法,那么他就是一个函数式接口。

eg:

public interface Runable {
    public abstract void run();
}

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

简化至 lambda 的步骤如下:

//外部类,接口
public class TestLove {
    public static void main(String[] args) {
        ILove iLove = new Love();
        iLove.love("zzz");

    }
}

interface ILove { void love(String a);}

class Love implements ILove {
    @Override
    public void love(String a) {
        System.out.println("I love --" + a);
    }
}
//静态内部类

public class TestLove {
    static class Love implements ILove {
        @Override
        public void love(String a) {
            System.out.println("I love --" + a);
        }
    }
    public static void main(String[] args) {
        ILove iLove = new Love();
        iLove.love("zzz");

    }
}

interface ILove { void love(String a);}

public class TestLove {

    public static void main(String[] args) {
        class Love implements ILove {
            @Override
            public void love(String a) {
                System.out.println("I love --" + a);
            }
        }

        ILove iLove = new Love();
        iLove.love("zzz");

    }
}

interface ILove { void love(String a);}
//匿名内部类

public class TestLove {

    public static void main(String[] args) {

        ILove iLove = new ILove() {
            @Override
            public void love(String a) {
                System.out.println("I love --" + a);
            }
        };
        iLove.love("zzz");
    }
}
interface ILove { void love(String a);}
//lambda表达式
ublic class TestLove {
    public static void main(String[] args) {

        ILove love = (String a)-> {
            System.out.println("I love --" + a);
        };
        love.love("zzz");

    }
}

interface ILove { void love(String a);}
//简化,去掉参数类型

public class TestLove {

    public static void main(String[] args) {

        ILove love = (a)-> {
            System.out.println("I love --" + a);
        };

        love.love("zzz");

    }
}

interface ILove { void love(String a);}
//简化括号
public class TestLove {

    public static void main(String[] args) {

        ILove love = a-> {
            System.out.println("I love --" + a);
        };

        love.love("zzz");

    }
}

interface ILove { void love(String a);}
//简化花括号,因为代码只有一行,有多行不可简化花括号
public class TestLove {

    public static void main(String[] args) {

        ILove love = a-> System.out.println("I love --" + a);
        love.love("zzz");

    }
}

interface ILove { void love(String a);}

总结:

  1. lambda 表达式代码只有一行的情况下才能简化为一行,有多行时必须用花括号包裹;
  2. 前提示接口为函数式接口(只包含一个方法);
  3. 多个参数也可以去掉参数类型,留就都留,去就都去,必须加上括号;

线程状态

image-20210411183018803

线程的方法

image-20210411183039107

停止线程

  1. 不推荐使用 JDK 提供的stop(); destroy();方法;
  2. 推荐线程自己停止;
  3. 建议使用一个标志位进行终止变量;
/**
 * 测试stop
 * 1. 建议线程正常停止--->利用次数;不建议死循环
 * 2. 建议使用标志位--->设置一个标志位
 * 3. 不要使用stop或者destory等过时或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++);
        }
    }

    //设置一个公开的方法停止线程,转换标志位
    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("该线程停止了");
                break;
            }
        }
    }
}

线程休眠

  1. sleep(时间) 指定当前线程阻塞的毫秒数;
  2. sleep 存在异常 InterruptException;
  3. sleep 时间达到后线程进入就绪状态;
  4. sleep 可以模拟网络延时,倒计时等;
  5. 每一个对象都有一个锁,sleep 不会释放锁;
//模拟倒计时 10s
public class TestSleep2 {
    public static void main(String[] args) throws InterruptedException {
        tenDown();
    }

    public static void tenDown() throws InterruptedException {
        int num = 10;
        while (true) {
            Thread.sleep(1000);
            System.out.println(num--);
            if (num <= 0) {
                break;
            }
        }
    }
}
//获取当前系统时间
public class TestSleep2 {
    public static void main(String[] args) throws InterruptedException {
        Date startTime = new Date(System.currentTimeMillis());
        while (true) {
            Thread.sleep(1000);
            System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
            startTime = new Date(System.currentTimeMillis());
        }

    }
}

线程礼让

  1. 礼让线程,让当前正在执行的线程暂停,但不阻塞;
  2. 将线程从运行状态转为就绪状态;
  3. 让 cpu 重新调度,礼让不一定成功!看 CPU 心情;
/**
 * 测试礼让程序
 * 礼让不一定成功,看CPU心情
 */
public class TestYield implements Runnable {
    public static void main(String[] args) {
        TestYield testYield =  new TestYield();

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

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "线程开始执行");
        Thread.yield();
        System.out.println(Thread.currentThread().getName() + "线程停止执行");
    }
}

//每次结果 都!不!一!样! ?????????  -_-|||

合并线程

  1. join 合并线程,待此线程执行完成后再执行其他线程,其他线程阻塞;
  2. 可以想象成插队;
  3. join 前是交替执行;并不是不执行!!!
public class TestJoin implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 500; i++) {
            System.out.println("★ VIP Thread ☆" + 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 == 200){
                thread.join(); // 插队
            }
            System.out.println("main" + i);
        }
    }
}

线程状态观测

Thread.state

/**
 * 观察测试线程的状态
 */
public class TestState {
    public static void main(String[] args) {
        Thread thread = new Thread(() -> {
                for (int i = 0; i < 5; i++) {
            try {
                Thread.sleep(1000);
            }catch (Exception 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); //RUN

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

        thread.start();  //死亡的线程不能再启动,必须再new一个

    }
}

多线程优先级

  1. java 提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,调度器按照优先级决定应该调度哪个线程来执行;
  2. 线程的优先级用数字表示,范围从 1~10 ;
    1. Thread.MAX_PRIORITY = 10;
    2. Thread.MIN_PRIORITY = 1;
    3. Thread.NORM_PRIORITY = 5;
  3. 使用以下方式改变或获取优先级 getPriority().setPriority(int xxx);

优先级低只是意味着获得调度的概率低,并不是高优先级必然先调用 (性能倒置问题);

public class TestPriority {
    public static void main(String[] args) {
        //主线程默认优先级
        System.out.println(Thread.currentThread().getName() + "---main---->" + 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(Thread.MAX_PRIORITY);  //MAX_PRIORITY=10
        t4.start();

        t5.setPriority(Thread.MIN_PRIORITY); // min 为最小 1
        t5.start();
    }
}

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

守护(daemon)线程

  1. 线程分为用户线程和守护线程;
  2. 虚拟机必须确保用户线程执行完毕;
  3. 虚拟机不用等待守护线程执行完毕;
  4. 如,后台记录操作日志,监控内存,垃圾回收等待;
//测试守护线程
public class TestDaemon {
    public static void main(String[] args) {
        God god = new God();
        Human human = new Human();

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

        thread.start();  // 用户线程启动
        new Thread(human).start();  //人类,用户线程启动

    }

}

// 上帝
class God implements Runnable{

    @Override
    public void run() {
        while(true){ // 按理来说不会结束 但作为守护线程在用户线程结束后 随之结束(可能会伴随虚拟机关闭的一点点延迟)
            System.out.println("legends never die!");
        }
    }
}

// 人类
class Human implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 365; i++) {
            System.out.println("happy live!");
        }
        System.out.println("Byebye, the worllllllllld!");  //nope!!!!!!!!!!
    }
}

线程同步

并发:同一个对象被多个线程同时操作;

处理多线程问题时,多线程访问一个对象,并且某些线程还想修改这个对象,这时候就需要线程同步。线程同步是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面线程使用完毕再让下一个线程使用

三个不安全案例

不安全买票

//不安全买票
// 线程不安全,有负数
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(true){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

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

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

        // 买票
        System.out.println(Thread.currentThread().getName() + "买到了" + ticketNum--);
    }
}

不安全取钱

// 不安全取钱
// 两个人去取钱
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) {
        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(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);
    }
}

不安全集合

public class UnSafeList {
    public static void main(String[] args) throws InterruptedException {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            new Thread(() -> {
                list.add(Thread.currentThread().getName());
            }).start();
        }
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(list.size());
    }
}

同步方法 - synchronized

  1. 由于我们可以通过 private 关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是 synchronized 关键字,它包括两种用法:synchronized 方法和 synchronized 块;

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

  2. synchronized 方法控制对“对象”的访问,每个对象对应一把锁,每个 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 ticketNum = 10;
    boolean flag = true; // 外部停止方式
    @Override
    public void run() {
        // 买票
        while(true){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
//synchronized
    private synchronized void buy() throws InterruptedException {
        // 判断是否有票
        if(ticketNum <= 0){
            flag = false;
            return;
        }

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

        // 买票
        System.out.println(Thread.currentThread().getName() + "买到了" + ticketNum--);
    }
}

同步块

同步块:synchronized(Obj) {}

Obj 称为同步监视器

  1. Obj 可以是任何对象,但是推荐使用共享资源作为同步监视器;
  2. 同步方法中无需指定同步监视器,因为同步方法的同步监视器就是 this,就是这个对象本身,或者是 class【反射中讲解】

同步监视器的执行过程:

  1. 第一个线程访问,锁定同步监视器,执行其中代码;
  2. 第二个线程访问,发现同步监视器被锁定,无法访问;
  3. 第一个线程访问完毕,解锁同步监视器;
  4. 第二个线程访问,发现同步监视器没有锁,然后锁定并反问;

synchronized () {}

// 两个人去取钱
public class UnsafeBank {
    public static void main(String[] args) {
        // 账户
        Account account = new Account(10000, "存款金额");
        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) {
        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(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);
        // 此时 Thread.currentThread().getName() = this.getName()
        System.out.println(this.getName() + "手里的钱:" + nowMoney);
    }
}
}
public class UnSafeList {
    public static void main(String[] args) throws InterruptedException {
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            new Thread(() -> {
                synchronized (list) {
                    list.add(Thread.currentThread().getName());
                }}).start();

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

JUC 安全类型的集合-CopyOnWriteArrayList

public class TestJUC {
    public static void main(String[] args) {
        CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
        for (int i = 0; i < 100; i++) {
            new Thread( () ->{
                list.add(Thread.currentThread().getName());
            } ).start();

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

    }
}

死锁

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

产生死锁的四个必要条件:

  1. 互斥:一个资源每次只能被一个进程使用
  2. 请求与保持:一个进程因请求资源而阻塞时,对已获得的资源保持不放
  3. 不剥夺:进程已获得的资源,在未用完之前,不能强行剥夺
  4. 循环等待:若干进程之间形成一种头尾相接的循环等待资源关系

上面四者只要想办法打破其中任意一个或者多个就可以避免死锁发生。

// 死锁:多个线程互相拥有对方需要的资源,形成僵持
public class DeadLock  {
    public static void main(String[] args) {
        Makeup moore = new Makeup(0, "Moore");
        Makeup dove = new Makeup(1, "Dove");
        moore.start();
        dove.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) {
            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 moore = new Makeup(0, "Moore");
        Makeup dove = new Makeup(0, "Dove");
        moore.start();
        dove.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) {
            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 moore = new Makeup(0, "Moore");
        Makeup dove = new Makeup(1, "Dove");
        moore.start();
        dove.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) {
            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 + "获得口红的锁");
            }

        }
    }
}

Lock 锁 - 可重入锁

//不安全
public class TestLock {
    public static void main(String[] args) {
        TestLock2 ticket = new TestLock2();

        new Thread(ticket, "小明").start();
        new Thread(ticket, "小二").start();
        new Thread(ticket, "阿黄").start();
    }
}

class TestLock2 implements Runnable {
    //票数
    int ticketNum = 10;


    @Override
    public void run() {
        while (true) {
            if (ticketNum > 0) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "------拿到了第" + ticketNum-- + "张票------");
            } else {
                break;
            }
        }
    }
}
//加锁.sleep不会释放锁对象,所以sleep请加到lock前面。
public class TestLock {
    public static void main(String[] args) {
        TestLock2 ticket = new TestLock2();

        new Thread(ticket, "小明").start();
        new Thread(ticket, "小二").start();
        new Thread(ticket, "阿黄").start();
    }
}

class TestLock2 implements Runnable {
    //票数
    int ticketNum = 10;

    //定义Lock锁
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lock.lock();
                if (ticketNum > 0) {
                    System.out.println(Thread.currentThread().getName() + "------拿到了第" + ticketNum-- + "张票------");
                }

                else {
                    break;
                }
            }finally {
                lock.unlock();
            }
        }
    }
}
class A{
  private final ReentrantLock lock = new ReenTrantLock();
  public void m(){
    lock.lock();
    try{
      // 保证线程安全的代码
    }
    finally{
            lock.unlock();
      // 如果同步代码有异常,要将unlock()写入finally语句块
    }
  }
}

synchronized 与 lock 的对比

  1. Lock 是显示锁,需要手动开启和关闭,synchronized 为隐式锁,出了作用域自动释放
  2. lock 只有代码块锁,synchronized 有代码块锁和方法锁
  3. 使用 lock 锁,jvm 将花费较少的时间来调度线程,性能更好。并且具有更好的扩展性
  4. 优先使用顺序
    • Lock > 同步代码块(已经进入方法体,分配了相应资源)> 同步方法(在方法体之外)

线程协作 - 生产者消费者问题

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

  1. 对于生产者,没有生产产品之前,要通知消费者等待,而生产了产品之后,有需要马上通知消费者消费
  2. 对于消费者,在消费之后,要通知生产者已经结束消费,需要生产新的产品以供消费
  3. 在生产者消费者问题中,仅有 synchronized 是不够的
    1. synchronized 可组织并发更新同一个共享资源,实现了同步
    2. synchronized 不能用来实现不同线程之间的消息传递(通信)

Java 提供了几个方法解决线程之间的通信问题

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

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

管程法

  1. 生产者:负责生产数据的模块(可能是方法、对象、线程、进程)

  2. 消费者:负责处理数据的模块(可能是方法、对象、线程、进程)

  3. 缓冲区:消费者不能直接使用生产者的数据,利用中间“缓冲区”

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

// 测试 生产者消费者模型 --> 利用缓冲区解决:管程法
// 有问题,会出现先消费后生产,要用队列实现
public class TestPC {
    public static void main(String[] args) {
        SynBuffer synBuffer = new SynBuffer();

        new Producer(synBuffer).start();
        new Consumer(synBuffer).start();
    }
}

// 生产者
class Producer extends Thread{
    SynBuffer buffer;
    public Producer(SynBuffer buffer){
        this.buffer = buffer;
    }
    // 生产

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("生产了" + i +"只鸡");
            try {
                buffer.push(new Chicken(i));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

// 消费者
class Consumer extends Thread{
    SynBuffer buffer;
    public Consumer(SynBuffer buffer){
        this.buffer = buffer;
    }

    // 消费

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                System.out.println("消费了-->" + buffer.pop().id +"只鸡");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

// 产品
class Chicken{
    int id; // 产品编号

    public Chicken(int id) {
        this.id = id;
    }
}

// 缓冲区
class SynBuffer{

    //容器大小
    Chicken[] chickens = new Chicken[10];
    // 容器计数器
    int count = 0;

    // 生产者放入产品
    public synchronized void push(Chicken chicken) throws InterruptedException {
        // 如果容器满了,需要等待消费者消费
        if(count == chickens.length){
            // 通知消费者消费,生产等待
            this.wait();
        }
        // 如果没有满,需要丢入产品
        chickens[count] = chicken;
        count ++;
        // 可以通知消费者消费了
        this.notifyAll();
    }

    // 消费者消费产品
    public synchronized Chicken pop() throws InterruptedException {
        // 判断能否消费
        if(count == 0){
            /// 等待生产者生产,消费者等待
            this.wait();
        }
        // 如果可以消费
        count --;
        Chicken chicken = chickens[count];
        // 吃完了,通知生产者生产
        this.notifyAll();

        return chicken;
    }
}

信号灯法

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;
    }
}

线程池

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

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

好处:

1. 提高响应速度(减少创建新线程的时间)
  1. 降低资源消耗(重复利用线程池中的线程,不需要每次都创建) 3. 便于线程管理 1. corePoolSize:最大线程数; 2. maxmumPoolSize:最大线程数; 3. keepAliveTime:线程没有任务时最多保持多长时间后会终止;

使用线程池

  1. jdk5.0 线程池相关 API :ExecutorService 和 Executors;
  2. ExecutorService :真正的线程池接口。常见子类 ThreadPoolExecutor;
    1. void execute(Runnable command) : 执行任务/命令,没有返回值,一般用来执行 Runnable;
    2. Future submit(Callable task): 执行任务,有返回值,一般用来执行 Callable;
    3. void shutdown(): 关闭连接池;
  3. Executors: 工具类、线程池的工厂类,用于创建并返回不同类型的线程池;
import java.util.concurrent.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());
        service.execute(new MyThread());
        // 2. 关闭连接
        service.shutdown();
    }
}

class   MyThread implements Runnable{

    @Override
    public void run() {
            System.out.println(Thread.currentThread().getName());
    }
}

总结

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class summary {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        new MyThread1().start();

        new Thread(new MyThread2()).start();

        FutureTask<Integer> futureTask = new FutureTask<Integer>(new MyThread3());
        new Thread(futureTask).start();
        Integer integer = futureTask.get();
        System.out.println(integer);
    }
}

// 1. 继承Thread类
class MyThread1 extends Thread{
    @Override
    public void run() {
        System.out.println("My Thread1");
    }
}
// 2. 实现Runnable接口
class MyThread2 implements Runnable{
    @Override
    public void run() {
        System.out.println("My Thread2");
    }
}
// 3. 实现Callable接口
class MyThread3 implements Callable<Integer>{
    @Override
    public Integer call() throws Exception {
        System.out.println("My Thread3");
        return 100;
    }
}
本文作者:shanX
本文链接:https://rhymexmove.github.io/2021/04/12/1d5c91f96393/
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可