多线程详解

多线程详解

线程、进程、多线程

程序,是指指令和数据的有序集合,其本身没有任何进行的含义,是一个静态的概念

进程,则是执行程序的一次执行过程,它是一个动态的概念,是系统资源分配的单位

通常在一个进程中可以包含若干个线程,当然一个进程中至少有一个线程,不然没有存在的意义,线程是CPU调度和执行的单位

注意:很多多线程是模拟出来的,真正的多线程是指有多个CPU,即多核,如服务器。如果是模拟出来的多线程,即在一个CPU的情况下,在同一个地点,CPU只能执行一个代码,因为切换的很快,所以就有同时执行的错局。

本章的核心概念

  1. 线程就是独立的执行路径
  2. 在程序运行时,即使没有自己创建线程,后台也会有多个线程,如主线程,gc线程
  3. main()称之为主线程,为系统的入口,用于执行整个程序
  4. 在一个进程中,如果开辟了多个线程,线程的运行由调度器安排调度,调度器是与操作系统紧密相关的先后顺序是不能人为的干预的
  5. 对同一份资源操作时,会存在资源抢夺的问题,需要加入并发控制
  6. 线程会带来额外的开销,如cpu调度时间,并发控制开销
  7. 每个线程在自己的工作内存交互,内存控制不当会造成数据不一致

创建线程

继承Thread类

创建线程方式一:继承Thread类,重写run方法,star开启线程

//创建线程方式一:继承Thread类,重写run方法,star开启线程
public class ThreadDemo extends Thread {
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println("--------------我在看代码------"+i);
        }
    }

    public static void main(String[] args) {
        //创建线程对象,star开启线程
        ThreadDemo threadDemo = new ThreadDemo();
        threadDemo.start();

        //主线程
        for (int i = 0; i < 2000; i++) {
            System.out.println("这边是主线程----"+i);
        }
    }
}

实现Runnable接口

创建线程方式二:

  1. 先实现Runnable接口;

  2. 实现run方法编写线程方法体;

  3. 创建线程对象,执行线程需要丢入runnable接口实现类,start方法开启。

推荐使用Runnable对象,因为Java单继承的局限性

public class TestTread02 implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 200; i++) {
            System.out.println("--------------我在看代码------"+i);
        }
    }

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


        for (int i = 0; i < 1000; i++) {
            System.out.println("这边是主线程----"+i);
        }

    }

}

案例:网图下载

方式一:

import org.apache.commons.io.FileUtils;

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

//练习Thread,实现多线程同步下载图片
public class TestThread extends Thread{

    private String url;
    private String name;

    public TestThread(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) {
        TestThread t1 = new TestThread("https://img2024.cnblogs.com/blog/3561673/202411/3561673-20241125191700187-1468694455.png", "1.jpg");
        TestThread t2 = new TestThread("https://img2024.cnblogs.com/blog/3561673/202411/3561673-20241125191715466-2054350322.png", "2.jpg");
        TestThread t3 = new TestThread("https://img2024.cnblogs.com/blog/3561673/202411/3561673-20241125191918757-296455428.jpg", "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 (IOException e) {
            e.printStackTrace();
            System.out.println("io异常,downloader方法出现问题");
        }
    }
}

方式二:

import org.apache.commons.io.FileUtils;

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

//练习Thread,实现多线程同步下载图片
public class TestThread implements Runnable{

    private String url;
    private String name;

    public TestThread(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) {
        TestThread t1 = new TestThread("https://img2024.cnblogs.com/blog/3561673/202411/3561673-20241125191700187-1468694455.png", "1.jpg");
        TestThread t2 = new TestThread("https://img2024.cnblogs.com/blog/3561673/202411/3561673-20241125191715466-2054350322.png", "2.jpg");
        TestThread t3 = new TestThread("https://img2024.cnblogs.com/blog/3561673/202411/3561673-20241125191918757-296455428.jpg", "3.jpg");

        new Thread(t1).start();
        new Thread(t2).start();
        new Thread(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方法出现问题");
        }
    }
}

小结

继承Thread类

  1. 子类继承Thread类具备多线程能力
  2. 启动线程,子类对象.start()
  3. 不建议使用,避免OOP单继承局限性

实现Runnable接口

  1. 实现接口Runnable具有多线程能力
  2. 启动线程:传入目标对象+Thread对象.start()
  3. 推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用
//一份资源
StartThread station = new StartThread();

//多个代理
new Thread(station,"小明").start();
new Thread(station,"老师").start();
new Thread(station,"小红").start();

实现Callable接口

创建线程方式三:

  1. 实现Callable接口,需要返回值类型
  2. 重写call方法,需要抛出异常
  3. 创建目标对象
  4. 创建执行服务:ExecutorService ser = Executors.newFixedThreadPool(1);
  5. 提交执行: Future result1 = ser.submit(t1);
  6. 获取结果: boolean r1 = result.get()
  7. 关闭服务:ser.shutdownNow();
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

public class TestCallable implements Callable<Boolean> {

    private String url;
    private String 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 ExecutionException, InterruptedException {

        TestCallable t1 = new TestCallable("https://img2024.cnblogs.com/blog/3561673/202411/3561673-20241125191700187-1468694455.png", "1.jpg");
        TestCallable t2 = new TestCallable("https://img2024.cnblogs.com/blog/3561673/202411/3561673-20241125191715466-2054350322.png", "2.jpg");
        TestCallable t3 = new TestCallable("https://img2024.cnblogs.com/blog/3561673/202411/3561673-20241125191918757-296455428.jpg", "3.jpg");


        //创建执行服务:
        ExecutorService ser = Executors.newFixedThreadPool(3);
        //提交执行:
        Future<Boolean> result1  = ser.submit(t1);
        Future<Boolean>  result2  = ser.submit(t2);
        Future<Boolean>  result3  = ser.submit(t3);
        //获取结果:
        boolean rs1 = result1.get();
        boolean rs2 = result2.get();
        boolean rs3 = result3.get();

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

        //关闭服务:
        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方法出现问题");
        }
    }
}

初识并发问题

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

//发现问题:多个线程操作同一个资源的情况下,线程不安全,数据紊乱
public class TestThread4 implements Runnable{
    //票数
    private int ticketNums = 10;

    @Override
    public void run() {
        while (true){
            if (ticketNums<=0)
                break;
            //模拟延时
            try {
                Thread.sleep(200);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"-->拿到了第"+ticketNums--+"票");
        }
    }

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

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

}

案例:龟兔赛跑

  1. 首先来个赛道距离,然后要离终点越来越近
  2. 判断比赛是否结束
  3. 打印出胜利者
  4. 龟兔赛跑开始
  5. 故事中是乌龟赢的,兔子需要睡觉,所以我们来模拟兔子睡觉
  6. 终于,乌龟赢得比赛
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);
            //如果比赛结束了就停止程序
            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;
    }

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

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

静态代理模块

静态代理模式总结:

  1. 真实对象和代理对象都要实现同一个接口
  2. 代理对象要代理真实角色

好处:

  1. 代理对象可以做很多真实对象做不了的事情
  2. 真实对象专注做自己的事情
public class StaticProxy {

    public static void main(String[] args) {
        WeddingCompanny weddingCompanny = new WeddingCompanny(new Man());
        weddingCompanny.HappyMarry();
    }

}

interface Marry{
    void HappyMarry();
}

//真实角色
class Man implements Marry{
    @Override
    public void HappyMarry() {
        System.out.println("Happy Marry!");
    }
}

//代理角色
class WeddingCompanny implements Marry{

    private Marry target;

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

    @Override
    public void HappyMarry() {
        before();
        this.target.HappyMarry();
        after();
    }

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

    private void before() {
        System.out.println("Marry之前,布置现场");
    }
}
public class StaticProxy {

    public static void main(String[] args) {

        Man man = new Man();

        new Thread(()->{
            System.out.println("===============Thread的lambda===============");
        }).start();

        new WeddingCompanny(new Man()).HappyMarry();
    }

}

interface Marry{
    void HappyMarry();
}

//真实角色
class Man implements Marry{
    @Override
    public void HappyMarry() {
        System.out.println("Happy Marry!");
    }
}

//代理角色
class WeddingCompanny implements Marry{

    private Marry target;

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

    @Override
    public void HappyMarry() {
        before();
        this.target.HappyMarry();
        after();
    }

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

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

Lamda表达式

为什么要是有lambda表达式?

  1. 避免匿名内部类定义过多
  2. 可以让你的代码看起来简洁
  3. 去掉了一堆没有意义的代码,只留下核心的逻辑

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

    //3.静态内部类
    static class Like2 implements ILike{
        @Override
        public void lambda() {
            System.out.println("I Like lambda2222!");
        }
    }

    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 lambda333333333!");
            }
        }
        like = new Like3();
        like.lambda();


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


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

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

//2.实现类
class Like implements ILike{
    @Override
    public void lambda() {
        System.out.println("I Like lambda!");
    }
}
public class TestLambda2 {
    public static void main(String[] args) {
        //1.lambda表示简化
        ILove love = (int a)->{
            System.out.println("I Love!-->"+a);
        };

        //简化1:参数类型
        love = (a)->{
            System.out.println("I Love ---->"+a);
        };

        //简化2:简化括号
        love = a->{
            System.out.println("I Love ---->"+a);
        };
        
        //简化3:去掉花括号
        love = a-> System.out.println("I Love ---->"+a);
        
        /*
        总结:
            1. lambda表达式只能有一行代码的情况下才能简化成为一行,如果有多行,那么就用代码块包裹
            2. 前提是函数式接口
            3. 多个参数也可以去掉参数类型,要去掉就都去掉,必须加上括号
         */

        love.love(52);
    }
}

interface ILove{
    void love(int a);
}

总结:

           1.  lambda表达式只能有一行代码的情况下才能简化成为一行,如果有多行,那么就用代码块包裹
           2.  前提是函数式接口
           3.    多个参数也可以去掉参数类型,要去掉就都去掉,必须加上括号

线程状态(五大状态)

线程方法

线程停止

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

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

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

        for (int i = 0; i < 1000; i++) {
            System.out.println("main "+i);
            if (i==900){
                //调用stop方法切换标志位,让线程停止
                testStop.stop();
                System.out.println("线程该结束了 "+i);
            }
        }
    }

}

线程休眠_sleep

import java.text.SimpleDateFormat;
import java.util.Date;

//模拟倒计时
public class TestSleep2 {

    //模拟倒计时
    public static void tenDown() throws InterruptedException {
        int num = 10;
        while (true){
            Thread.sleep(1000);
            System.out.println(num--);
            if (num==0){
                break;
            }
        }
    }

    public static void main(String[] args) {

        try {
            tenDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

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

    }
}

线程礼让_yield

//礼让不一定成功,看CPU心情
public class TestYield {

    public static void main(String[] args) {
        MyYield myYield = new MyYield();

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

}

class MyYield implements Runnable{

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

线程强制执行_join

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==200){
                thread.join();
            }
            System.out.println("main "+i);
        }
    }
    
}

观测线程状态

public class TestState {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(()->{
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("/////////");
        });

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

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

        //只要线程不终止,就一直输出状态
        while (state != Thread.State.TERMINATED){
            Thread.sleep(1000);
            state = thread.getState();//更新线程状态
            System.out.println(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 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);
        t4.start();

//        t5.setPriority(-1);
//        t5.start();
//
//        t6.setPriority(11);
//        t6.start();
    }
}

class MyPriority implements Runnable{

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

先设置优先级再启动

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

守护线程

//上帝守护你
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("God保佑着你!");
        }
    }
}

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

线程同步机制

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

形成条件:队列 +

三大不安全案例

不安全的买票

//不安全的买票
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 ticketNum = 10;
    boolean flag = true;
    @Override
    public void run() {
        //买票
        while (flag){
            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 mom = new Drawing(account, 50, "母亲");

        you.start();
        mom.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;
        }

        //sleep可以放大问题的发生性
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

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

        System.out.println(account.name+"余额为:"+account.money);
        //  this.getName()相当于 Thread.currentThread().getName()
        System.out.println(this.getName()+"手里的钱:"+nowMoney);
    }
}

不安全的集合

import java.util.ArrayList;
import java.util.List;

public class UnsafeList {

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

        System.out.println(list.size());
    }

}

同步方法及同步块

线程同步

同步方法

同步方法弊端:

方法里面有需要修改的内容才需要锁。锁的太多,浪费资源

例如:一般只读的代码不需要锁,修改的代码才需要锁

锁谁取决于你们同时操作的对象是谁(哪个类的属性会发生变化,就锁哪个类的对象)

同步方法 synchronized

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 ticketNum = 10;
    boolean flag = true;
    @Override
    public void run() {
        //买票
        while (flag){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //synchronized 同步方法,锁的是this
    private synchronized void buy() throws InterruptedException {
        //判断是否有票
        if (ticketNum<=0){
            flag = false;
            return;
        }
        //模拟延时
        Thread.sleep(100);
        //买票
        System.out.println(Thread.currentThread().getName()+"-->拿到了第 "+ ticketNum-- +"票");
    }
}

同步方法块 synchronized(){}

//两个人去银行取钱,账户
public class UnsafeBank {
    public static void main(String[] args) {
        //账户
        Account account = new Account(1000, "资金");
        Drawing you = new Drawing(account, 50, "你");
        Drawing mom = new Drawing(account, 50, "母亲");

        you.start();
        mom.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;
            }

            //sleep可以放大问题的发生性
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

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

            System.out.println(account.name+"余额为:"+account.money);
            //  this.getName()相当于 Thread.currentThread().getName()
            System.out.println(this.getName()+"手里的钱:"+nowMoney);
        }

    }
}
import java.util.ArrayList;
import java.util.List;

public class UnsafeList {

    public static void main(String[] args) {
        List<String> list = new ArrayList<String>();
        for (int i = 0; i < 10000; i++) {
            new Thread(()->{
                synchronized (list){
                    list.add(Thread.currentThread().getName());
                }
            }).start();
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(list.size());
    }

}

CopyOnWriteArrayList

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(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(list.size());
    }

}

死锁

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) {
            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(1000);
            }
            synchronized (lipStick){  //获得口红的锁
                System.out.println(this.girlName+"获得口红的锁");
            }
        }
    }
}

Lock锁

import java.util.concurrent.locks.ReentrantLock;

public class TestLock {

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

    }
}

class TestLock2 implements Runnable{

    int ticketNum = 10;

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

    @Override
    public void run() {
        while (true){
            lock.lock();
            try {
                if (ticketNum<=0){
                    return;
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(ticketNum--);
            }finally {
                //解锁
                lock.unlock();
            }

        }
    }
}

线程协作


生产者消费者问题

管程法

//测试: 生产者消费者模型-->利用缓冲区解决:管程法
//生产者,消费者,产品,缓冲区
public class TestPC {

    public static void main(String[] args) {
        SynContainer container = new SynContainer();
        new Productor(container).start();
        new Consumer(container).start();

    }

}

//生产者
class Productor extends Thread{
    SynContainer container;

    public Productor(SynContainer container){
        this.container = container;
    }

    //生产
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("生产了"+i+"只鸡");
            container.push(new Chicken(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[100];
    //容器计数器
    int count = 0;

    //生产者放入产品
    public synchronized void push(Chicken chicken){
        //如果容器满了,就需要等消费者消费
        if (count==chickens.length){
            //通知消费者消费,生产者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //如果没有满,我们就需要丢入产品
        chickens[count] = chicken;
        count++;

        //可以通知消费之消费了
        this.notifyAll();
    }

    //消费者消费产品
    public synchronized Chicken pop(){
        //判断能否消费
        if (count==0){
            //通知生产者生产,消费者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //如果可以消费
        count--;
        Chicken chicken = chickens[count];

        //吃完了,通知生产者生产
        this.notifyAll();
        return chicken;
    }

}

信号灯法

//测试生产者消费者问题2:信号灯法,标志位解决
public class TestPC2 {

    public static void main(String[] args) {
        TV tv = new TV();
        new Player(tv).start();
        new Watcher(tv).start();
    }

}

//生产者-->演员
class Player extends Thread{
    TV tv;
    public Player(TV tv){
        this.tv = tv;
    }
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if (i%2==0){
                this.tv.play("快乐大本营播放中");
            }else {
                this.tv.play("抖音");
            }
        }
    }
}

//消费者-->观众
class Watcher extends Thread{
    TV tv;
    public Watcher(TV tv){
        this.tv = tv;
    }
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            tv.watch();
        }
    }
}

//产品-->节目
class TV{
    //演员表演,观众等待
    //观众观看,演员等待
    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.voice = voice;
        this.notifyAll();
        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;
    }

}

线程池


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

总结

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

//回顾总结线程的创建
public class ThreadNew {


    public static void main(String[] args) {
        new MyThread1().start();
        
        new Thread(new MyThread2()).start();

        FutureTask<Integer> futureTask = new FutureTask<Integer>(new MyThread3());
        new Thread(futureTask).start();
        try {
            futureTask.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

}

class MyThread1 extends Thread{
    @Override
    public void run() {
        System.out.println("MyThread1---Thread");
    }
}

class MyThread2 implements Runnable{
    @Override
    public void run() {
        System.out.println("MyThread2--------->Runnable");
    }
}

class MyThread3 implements Callable<Integer>{
    @Override
    public Integer call() throws Exception {
        System.out.println("MyThread3!!!!!!!Callable");
        return 110;
    }
}
posted @ 2024-11-27 00:40  沙皮狗J  阅读(75)  评论(0)    收藏  举报