JavaSE学习心得——多线程

线程简介

多任务

在这里插入图片描述

多线程

在这里插入图片描述
在这里插入图片描述

线程,进程,多线程

在这里插入图片描述
总结
在这里插入图片描述

线程创建

三种实现方式

在这里插入图片描述

继承Thread类

  • run(),只有主线程一条执行路径
package thread;

//创建线程的方法一:继承Thread类,重写run()方法,调用start开启线程
public class TestThread1 extends Thread{
    @Override
    public void run() {
        //run方法线程体
        for (int i = 0; i < 10; i++) {
            System.out.println("我在看代码——"+i);
        }
    }

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

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

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

}

在这里插入图片描述

  • start(),多条执行路径,主线程和子线程并行交替执行
package thread;

//创建线程的方法一:继承Thread类,重写run()方法,调用start开启线程
public class TestThread1 extends Thread{
    @Override
    public void run() {
        //run方法线程体
        for (int i = 0; i < 10; i++) {
            System.out.println("我在看代码——"+i);
        }
    }

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

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

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

}

在这里插入图片描述

实现Runnable接口

package thread;

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

    public static void main(String[] args) {
        //创建runnable接口的实现对象
        TestThread2 testThread2= new TestThread2();

        //创建线程对象,通过线程对象来开启我们的线程代理
        /*Thread thread=new Thread(testThread2);
        thread.start();*/
        new Thread(testThread2).start();

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

在这里插入图片描述
【案例1】模拟抢票——三个问题

package thread;

public class Thread4 implements Runnable {

    //票数
    private int ticketNum = 10;

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

    public static void main(String[] args) {
        Thread4 ticket=new Thread4();
        new Thread(ticket,"小明").start();
        new Thread(ticket,"老师").start();
        new Thread(ticket,"黄牛").start();
    }
}

在这里插入图片描述
【案例2】龟兔赛跑
在这里插入图片描述

package thread;

public class Race implements Runnable {
    //胜利者
    private String winner;

    @Override
    public void run() {
        for (int i = 0; i <= 100; i++) {
            if (Thread.currentThread().getName().equals("兔子")&&i%10==0) {//让兔子每跑10步睡一会
                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 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();
    }
}

在这里插入图片描述

总结
在这里插入图片描述

实现Callable接口

在这里插入图片描述

Lamda表达式

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

package StudentsInformationBase.lambda;

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

    //3.静态内部类
    static class Like2 implements ILike{

        @Override
        public void lambda() {
            System.out.println("我爱Lambda2");
        }
    }

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

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

       //4.局部内部类
        class Like3 implements ILike{

            @Override
            public void lambda() {
                System.out.println("我爱Lambda3");
            }
        }
        like=new  Like3();
        like.lambda();

        //5.匿名内部类
        like=new ILike() {
            @Override
            public void lambda() {
                System.out.println("我爱Lambda4");
            }
        };
        like.lambda();

        //6.lambda表达式
        like = ()->{
            System.out.println("我爱Lambda5");
        };
        like.lambda();

    }

}

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

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

    @Override
    public void lambda() {
        System.out.println("我爱Java1");
    }
}

在这里插入图片描述

package StudentsInformationBase.lambda;

public class TestLambda2 {
    public static void main(String[] args) {

            //1.lambda表示简化
            ILove love=(int a)->{
                System.out.println("I Love You"+a);
            };
            //简化1.参数类型
            love=(a) -> {
                System.out.println("I Love You"+a);
            };
            //简化2.简化括号
            love=a -> {
                System.out.println("I Love You"+a);
                System.out.println("I Love You——>too");
            };
            //简化3.去掉花括号:只有一行时可以用
            love=a -> System.out.println(a);
            love.love(2021);
    }
}

interface ILove{
    void love(int a);
}

总结

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

静态代理(线程类底层实现思想)

——第一次体会到Java接口和静态代理思想的强大,牛哇
在这里插入图片描述

package StudentsInformationBase.Proxy;

//静态代理模式总结:
//真实对象和代理对象都要实现同一个接口
//代理对象要代理真实的角色

//好处:
   //代理对象可以做很多真实对象做不了的事情
   //真实的对象专注做自己的事情
public class staticProxy {
    public static void main(String[] args) {
        WeddingCompany weddingCompany=new WeddingCompany(new You());
        weddingCompany.HappyMarry();
    }
}
interface Marry{
    //人间四大喜事
     //久旱逢甘霖
     //他乡遇故知
     //洞房花烛夜
     //金榜题名时
    void HappyMarry();

}

//真实角色,你去结婚
class You implements Marry{

    @Override
    public void HappyMarry() {
        System.out.println("要结婚了,超级开心!");
    }
}
//代理角色,帮助你结婚
class WeddingCompany implements Marry{

    //代理谁——》真实的角色
    private Marry target;//同基本类型

    public WeddingCompany(Marry target) {
        this.target = target;//这就是真实的对象
    }

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

    //牛的来了:婚庆公司可以有自己的业务,封装的思想
    private void before() {
        System.out.println("结婚之前,布置现场");
    }

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

同线程类比较

//Thread类实现了Runnable接口,成为代理类
 new Thread(()-> System.out.println("我爱你")).start();

 new WeddingCompany(new You()).HappyMarry();

线程状态

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

线程停止

在这里插入图片描述

package thread;


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

    }

    //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("线程该停止了");
            }

        }


    }
}

线程休眠

在这里插入图片描述

  • 模拟网络延时:放大问题的发生性:多个线程操作第一个对象时,是否存在问题?通过让线程休眠,来“放大问题”,进行解决
package thread;

//模拟网络延时:放大问题的发生性
public class Thread_Sleep1 implements Runnable {

    //票数
    private int ticketNum = 10;

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

    public static void main(String[] args) {
        Thread_Sleep1 ticket=new Thread_Sleep1();
        new Thread(ticket,"小明").start();
        new Thread(ticket,"老师").start();
        new Thread(ticket,"黄牛").start();
    }
}

  • 模拟倒计时/时钟显示
package thread;

//模拟倒计时
public class Thread_Sleep2 {

    public static void main(String[] args) {
        try {
            tenDown();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void tenDown() throws InterruptedException {
        int num = 10;

        while (true) {
            Thread.sleep(1000);
            System.out.println(num--);
            if (num <= 0) {
                break;
            }
        }

    }
}

package thread;

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

//时间显示
public class Thread_Sleep3 {

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

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

         }

    }


}

线程礼让

在这里插入图片描述

package thread;

//测试礼让线程
//礼让不一定成功,看CPU心情
public class ThreadYield {
    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()+"线程结束");
    }
}

线程强制执行

在这里插入图片描述

package thread;

//测试join方法——>想象为插队
public class ThreadJoin implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 300; i++) {
            System.out.println("VIP线程来了"+i);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        //启动我们的线程
        ThreadJoin threadJoin=new ThreadJoin();
        Thread thread= new Thread(threadJoin);
        thread.start();

        //主线程
        for (int i = 0; i < 1000; i++) {
            System.out.println("main"+i);
            if (i==200) {
                    thread.join();
                }
            }

        }
    }


在这里插入图片描述
在这里插入图片描述

观察线程状态

在这里插入图片描述

package thread;

//观察测试线程的状态
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(100);
            state=thread.getState();//更新线程状态
            System.out.println(state);//输出状态

        }
        thread.start();//尝试再启动线程

    }
}

测试线程的优先级

在这里插入图片描述

package thread;

//测试线程的优先级
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);

        //设置优先级
        t1.start();

        t2.setPriority(1);
        t2.start();

        t3.setPriority(4);
        t3.start();

        t4.setPriority(Thread.MAX_PRIORITY);//MAX_PRIORITY=10
        t4.start();

        t5.setPriority(11);
        t5.start();
    }

}
class MyPriority implements Runnable{

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

在这里插入图片描述

守护线程

在这里插入图片描述

package thread;

//测试守护线程
//上帝守护你
public class TestDaemon {
    public static void main(String[] args) {
        god god=new god();
        you you=new you();

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

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

        new Thread(you).start();//你 用户线程启动。。。
    }
}
//上帝
class god implements Runnable{

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


//你
class you implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 36500; i++) {
            System.out.println("你一生开心的活着");
        }
        System.out.println("-===========goodbye world!===============-");
    }
}

在这里插入图片描述

线程同步

多个线程操作同一个资源
在这里插入图片描述
形成的条件:队列+锁
在这里插入图片描述

三大不安全案例

  • 买票,同时操作一个资源
package syn;

//不安全的买票
//线程不安全,有-1
public class UnSafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket station=new BuyTicket();
        new Thread(station,"小明").start();
        new Thread(station,"老师").start();
        new Thread(station,"黄牛").start();
    }

}
class BuyTicket implements Runnable{

    //票
    private int ticketNums=10;
    boolean flag=true;//外面停止方式
    @Override
    public void run() {
        //卖票
        while (flag){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void buy() throws InterruptedException {
        //判断是否有票
        if (ticketNums<=0){
            flag=false;
            return;
        }
        //模拟延时
        Thread.sleep(1000);
        //买票
        System.out.println(Thread.currentThread().getName()+"拿到票"+ticketNums--);
    }


}

在这里插入图片描述

  • 取钱,操作同一个资源
    super(name)重点理解
package syn;

//不安全的买票
//两个人去银行取钱
public class UnSafeBank {
    public static void main(String[] args) {
        //账户
        Account account = new Account(100,"结婚基金");

        Drawing you= new Drawing(account,50,"你");
        Drawing girlfriend= new Drawing(account,100,"girlfriend");

        you.start();
        girlfriend.start();
    }

}

//账户
class Account{
    int monkey;//余额
    String name;//卡名

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

//银行:模拟取钱
class Drawing extends Thread{
    Account account;//账户
    //取了多少钱
    int drawMonkey;
    //现在手里有多少钱
    int nowMonkey;

    public Drawing(Account account,int drawMonkey,String name){
        super(name);//因为Thread父类有name属性,想调用,所以使用super调用父类构造器,然后下面代码就可以用了。Thread.currentThread().getName() = this.getName()
        this.account=account;
        this.drawMonkey=drawMonkey;
    }

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

        }
        //卡内余额 = 余额 - 你取的钱
        account.monkey=account.monkey-drawMonkey;
        //你手里的钱
        nowMonkey=nowMonkey+drawMonkey;

        System.out.println(account.name+"余额为:"+account.monkey);
        //Thread.currentThread().getName() = this.getName()
        System.out.println(this.getName()+"手里的钱:"+nowMonkey);//this指代thread父类


    }
}

在这里插入图片描述

  • 集合
package 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 < 10000; i++) {
            new Thread(()->{
               list.add(Thread.currentThread().getName());
            }).start();
        }
        System.out.println(list.size());
    }
}

在这里插入图片描述
显然一万的线程有丢失发生,就是因为有多个线程同时覆盖了同一个list元素——因为线程的内存都是各种的,互不影响

同步方法以及同步块

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

取票——给方法加锁

在这里插入图片描述
在这里插入图片描述

取钱——给代码块加锁,不是给this(银行)加锁

package syn;

//不安全的买票
//两个人去银行取钱
public class UnSafeBank {
    public static void main(String[] args) {
        //账户
        Account account = new Account(1000,"结婚基金");

        Drawing you= new Drawing(account,50,"你");
        Drawing girlfriend= new Drawing(account,100,"girlfriend");

        you.start();
        girlfriend.start();
    }

}

//账户
class Account{
    int monkey;//余额
    String name;//卡名

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

//银行:模拟取钱
class Drawing extends Thread{
    Account account;//账户
    //取了多少钱
    int drawMonkey;
    //现在手里有多少钱
    int nowMonkey;

    public Drawing(Account account,int drawMonkey,String name){
        super(name);//因为Thread父类有name属性,想调用,所以使用super调用父类构造器,然后下面代码就可以用Thread.currentThread().getName() = this.getName()
        this.account=account;
        this.drawMonkey=drawMonkey;
    }

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

            }
            //Sleep可以放大问题的发生性
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //卡内余额 = 余额 - 你取的钱
            account.monkey=account.monkey-drawMonkey;
            //你手里的钱
            nowMonkey=nowMonkey+drawMonkey;

            System.out.println(account.name+"余额为:"+account.monkey);
            //Thread.currentThread().getName() = this.getName()
            System.out.println(this.getName()+"手里的钱:"+nowMonkey);


        }

    }
}

在这里插入图片描述

集合

package syn;

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

//线程不安全的集合
public class UnsafeList {
    public static void main(String[] args) throws InterruptedException {
        List<String> list= new ArrayList<String>();
        for (int i = 0; i < 10000; i++) {
            new Thread(()->{
                synchronized (list){
                    list.add(Thread.currentThread().getName());
                }
            }).start();
        }
        Thread.sleep(1000);//防止其他线程还没执行完,主线程已经执行完了就打印list的数量
        System.out.println(list.size());
    }
}

在这里插入图片描述

CopyOnWriteArrayList——JUC安全类型的集合

package syn;

import java.util.concurrent.CopyOnWriteArrayList;

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

在这里插入图片描述

死锁

在这里插入图片描述

  • 女孩子爱化妆
package Lock;

//死锁:多个线程互相抱着对方需要的资源,然后形成僵持
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(1000);
                synchronized (lipStick) {//一秒后想获得口红的锁
                    System.out.println(this.name + "获得口红的锁");
                }
            }
        }
    }
}

在这里插入图片描述
解决办法,将锁拿到外面

package Lock;

//死锁:多个线程互相抱着对方需要的资源,然后形成僵持
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(1000);
            }
            synchronized (lipStick) {//一秒后想获得口红的锁
                System.out.println(this.name + "获得口红的锁");
            }
        }
    }
}

在这里插入图片描述
在这里插入图片描述

Lock(锁)

在这里插入图片描述
在这里插入图片描述

package Lock;

import java.util.concurrent.locks.ReentrantLock;

//测试lock锁
public class Lock {
    public static void main(String[] args) {
        TestLock testLock=new TestLock();
        new Thread(testLock).start();
        new Thread(testLock).start();
        new Thread(testLock).start();
    }
}

class TestLock implements Runnable{

    //票
    int ticketNums=10;

    //定义lock锁——可重入锁
    private final ReentrantLock lock=new ReentrantLock();
    @Override
    public void run() {
        while (true){
            try {
                lock.lock();//加锁
                if (ticketNums>0){
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(ticketNums--);
                }else {
                    break;
                }
            } finally {
                //解锁
                lock.unlock();
            }

        }

    }
}

在这里插入图片描述
在这里插入图片描述

生产者,消费者问题

在这里插入图片描述
在这里插入图片描述

  • 管程法
    在这里插入图片描述
  • 信号灯法
    在这里插入图片描述

管程法

package Lock;

//测试:生产者消费者模型-->利用缓冲区解决:管程法

//生产者,消费者,缓冲区
public class TestPC {
    public static void main(String[] args) {
        SynContainer container=new SynContainer();
        new Productor(container).start();
        new Customer(container).start();
    }
}

//生产者
class Productor extends Thread{
    SynContainer container;
    public Productor(SynContainer container){
        this.container=container;
    }

    //生产
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("生产了"+i+"只鸡");
            container.push(new Chicken(i));
        }

    }
}

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

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

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消费了-->"+container.pop().id+"只鸡");

        }
    }
}

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

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

//缓冲区
class SynContainer{

    //需要一个容器的大小
   Chicken[] chickens= new Chicken[10];
   //容器计数器
    int count=0;

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

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

        //通知消费者来进行消费了
        this.notifyAll();
    }

    //消费者消费产品
    public synchronized Chicken pop(){
        //判断能否消费
        if (count==0){
            //等待生产者生产,消费者等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果可以消费
        count--;
        Chicken chicken=chickens[count];

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


    }




}

在这里插入图片描述

信号灯法

package Lock;

//测试生产者消费者问题2:信号灯法,标志位解决
public class TestPC2 {
    public static void main(String[] args) {
        TV tv=new TV();
        new Player(tv).start();
        new Watcher(tv).start();
    }
}

//生产者-->演员
class Player extends Thread{
    TV tv;
    public Player(TV tv){
        this.tv=tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            if (i%2==0){
                this.tv.play("极限挑战播放中");
            }else {
                this.tv.play("抖音记录美好生活");
            }
        }
    }
}

//消费者-->观众
class Watcher extends Thread{
    TV tv;
    public Watcher(TV tv){
        this.tv=tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            tv.watch();
        }
    }
}

//产品-->节目
class TV{
    //演员表演,观众等待 T
    //观众观看,演员等待 F
    String voice;
    Boolean flag=true;

    //表演
    public synchronized void play(String voice){
        if (!flag){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("演员表演了:"+voice);
        //通知观众观看
        this.notify();//通知唤醒
        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.notify();
        this.flag=!this.flag;

    }

}

在这里插入图片描述

线程池

在这里插入图片描述
在这里插入图片描述

package Lock;

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

    }
}

在这里插入图片描述

总结

package Lock;

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

//回顾总结线程的创建
public class Summary {
    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 {
            Integer integer= futureTask.get();
            System.out.println(integer);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }
}

//1.继承Thread类
class MyThread1 extends Thread{
    @Override
    public void run() {
        System.out.println("MyThread1");
    }
}

//2.实现Runnable接口
class MyThread2 implements Runnable{

    @Override
    public void run() {
        System.out.println("MyThread2");
    }
}

//3.实现Callable接口
class MyThread3 implements Callable<Integer>{

    @Override
    public Integer call() throws Exception {
        System.out.println("MyThread3");
        return 100;

    }
}

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

至南岸

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值