即使再小的帆也能远航,不断学习,不断总结,不断进步!

线程简介

一句话来描述
进程:系统中正在运行的一个应用程序,程序是静态的,进程是动态的
线程:系统CPU调度和执行的基本单位
进程和线程的关系:一个进程至少有一个线程

线程实现

继承Thread类

//继承Thread类,重写run方法
public class MyThread_1 extends Thread {
    //线程入口
    @Override
    public void run() {
        //线程体
        for (int i = 1; i <=5 ; i++) {
            System.out.println("第"+i+"次执行");
        }
    }

    public static void main(String[] args) {
        //创建线程对象
        MyThread_1 thread = new MyThread_1();
       //执行start()方法开启线程
        thread.start();
    }
}

实现Runnable接口

推荐使用:避免单继承局限性,方便同一个对象被多个线程使用

//实现Runnable接口创建线程
public class MyThread_2 implements Runnable {
    @Override
    public void run() {
        //线程体
        for (int i = 1; i <=5 ; i++) {
            System.out.println("第"+i+"次执行");
        }
    }

    public static void main(String[] args) {
        //创建实现类对象
        MyThread_2 myThread2 = new MyThread_2();
        //创建代理类对象
        Thread thread = new Thread(myThread2);
        //启动线程
        thread.start();
    }
}

使用匿名内部类的方式

//实现Runnable接口创建线程
public class MyThread_2  {
    public static void main(String[] args) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                //线程体
                for (int i = 1; i <= 5; i++) {
                    System.out.println("第" + i + "次执行");
                }
            }
        }).start();  
    }
}

使用lamda的方式

//实现Runnable接口创建线程
public class MyThread_2_2 {
    public static void main(String[] args) {
        
        //使用Lamda来实现,因为Runnable接口中只有一个run()方法,属于函数式接口
        new Thread(() -> {
            //线程体
            for (int i = 1; i <= 5; i++) {
                System.out.println("第" + i + "次执行");
            }
        }).start();
    }
}
Lamda表达式
//推导lamdba表达式
public class TestLambda {
    //静态内部类
    static class Like2 implements ILike{
        @Override
        public void lambda() {
            System.out.println("I like lambda-2");
        }
    }
    public static void main(String[] args) {
        ILike like1 = new Like1();
        like1.lambda();
        
        like1 = new Like2();
        like1.lambda();
        
        //局部内部类
        class Like3 implements ILike{
            @Override
            public void lambda() {
                System.out.println("I like lambda-3");
            }
        }
        like1 = new Like3();
        like1.lambda();
        
        //匿名内部类,没有类的名称,必须借助于接口或者父类
        like1 = new ILike() {
            @Override
            public void lambda() {
                System.out.println("I like lambda-4");
            }
        };
        like1.lambda();
        
        //使用lamdba表达式
        like1 = ()->{
            System.out.println("I like lambda-5");
        };
        like1.lambda();
    }


}
//定义一个函数式接口
interface ILike{
    void lambda();
}
//实现类
class Like1 implements ILike{

    @Override
    public void lambda() {
        System.out.println("I like lambda-1");
    }
}
静态代理模式

举例子:新人举行婚礼、婚庆公司代办婚礼

/**
 * 静态代理模式总结:
 * 代理角色和真实角色要实现同一个接口
 * 代理对象要代理真实角色
 * 好处:
 * 代理对象可以做真实对象做不了的事情
 * 真实对象可以专心做自己的事情
 */
public class StaticProxy {
    public static void main(String[] args) {

        new WeddingCompany(new You()).HappyMarry();
        //对比Thread和Runnable接口
        //new Thread(new MyThread()).start;
    }

}
//结婚
interface Marry {   //Runnable接口  
    void HappyMarry();   //run()方法
}
//真实角色,你,你要结婚
class You implements Marry {   //自定义线程实现Runnable接口
    @Override
    public void HappyMarry() {
        System.out.println("你要结婚");
    }
}
//代理角色,婚庆公司,帮助你结婚
class WeddingCompany implements Marry {  //Thread实现Runnable接口
    //代理谁==> 真实目标对象
    private Marry target;                //private Runnable target;

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

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

    public void befor() {
        System.out.println("结婚之前,布置现场");
    }

    public void after() {
        System.out.println("结婚之后,收尾款");
    }
}
Thread类和Runnable接口的关系
/**
 * Thread类是Runnable接口的子类
 * 多线程的设计之中,使用了静态代理的设计模式,用户自定义的线程主体(真实对象)只是负责核心功能的实现,
 * 而所有的辅助实现全部交由Thread类(代理对象)来处理。
 * 多线程开发的实质上是在于多个线程可以进行同一资源的抢占,
 * 那么Thread主要描述的是线程,而资源的描述是通过Runnable完成的
 */
public class test{
    public static void main(String[] args) {
        //真实对象
        MyThread myThread = new MyThread();
        //代理对象
        Thread thread = new Thread(myThread);
        //代理对象额外提供的方法
        thread.start();
    }
}
//真实对象-用户自定义的线程
class MyThread implements Runnable{
    @Override
    public void run() {
        System.out.println("核心功能的实现");
    }
}

初识并发问题
/**
 * 买票的小例子
 * 发现问题:多个线程同时操作一个资源,线程不安全,出现数据紊乱
 */
public class ThreadTest implements Runnable{
    //定义10张火车票
    private int ticket = 10;

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

    public static void main(String[] args) {
        ThreadTest test = new ThreadTest();
        new Thread(test,"A").start();
        new Thread(test,"B").start();
        new Thread(test,"C").start();
    }
}
龟兔赛跑问题
//小案例:龟兔赛跑
public class ThreadTest 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 flage = gameOver(i);
            //如果比赛结束,就停止跑步
            if(flage){
                break;
            }
            System.out.println(Thread.currentThread().getName()+"===>跑了"+i+"步");
        }
    }
    //判断是否完成比赛
    private boolean gameOver(int steps){
        //判断是否有胜利者
        if(winner!=null){ //已经存在胜利者
            return true;
        }
        //判断是否跑完100步
        if(steps>=100){
           winner = Thread.currentThread().getName();
            System.out.println("胜利者是:"+winner);
            return true;
        }
        return false;
    }

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

实现Callable接口

//实现Callable接口创建线程
public class TestThread implements Callable<Boolean> {
    @Override
    public Boolean call() throws Exception {
        for (int i = 0; i <= 10; i++) {
            System.out.println("第"+i+"次执行");
        }
        //有返回值
        return false;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestThread test = new TestThread();
        //创建执行服务
        ExecutorService executorService = Executors.newFixedThreadPool(1);
        //提交服务
        Future<Boolean> future = executorService.submit(test);
        //获取返回的结果
        Boolean b = future.get();
        //关闭服务
        executorService.shutdown();
    }
}

线程状态

创建状态
就绪状态
运行状态 阻塞状态
死亡状态

线程停止

使用标志位进行终止变量,当flag=false的时候,终止线程运行

public class MyThread_4 implements Runnable {
    //线程中定义线程体使用的标识
    private boolean flag = true;
    //对外提供方法改变标识
    public void stop() {
        this.flag = false;
    }

    @Override
    public void run() {
        int i = 0;
        //线程体使用标识
        while (flag) {
            System.out.println("run......thread"+i++);
        }
    }

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

        for (int i = 1; i <=100; i++) {
            if (i == 90) {
                thread1.stop();
                System.out.println("线程该停止了");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.out.println("main线程执行" + i);
        }
    }
}

2020-03-17_102208.png

线程休眠

  • sleep(时间):指定当前线程阻塞的毫秒数
  • sleep存在异常InterruptedException
  • sleep时间达到后线程进入就绪状态
  • 每一对象都有一个锁,sleep不会释放锁
可以使用Thread.sleep()或者使用TimeUnit

线程礼让

  • 礼让线程,让当前正在执行的线程暂停,但不阻塞
  • 将线程从运行状态转为就绪状态
  • 让CPU重新调度,礼让不一定成功
public class MyThread_5 {
    public static void main(String[] args) {
        MyThread thread1 = new MyThread();
        new Thread(thread1,"a线程").start();
        new Thread(thread1,"b线程").start();

    }

}

class MyThread implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+
                "线程开始执行");
        Thread.yield();
        System.out.println(Thread.currentThread().getName()+
                "线程结束执行");
    }
}

2020-03-17_111312.png

线程强制执行

  • join合并线程,待插入的线程执行完毕后,再执行原来的线程
public class TestJoin implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 10; 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 < 100; i++) {
            if(i==20){
                thread.join();
            }
            System.out.println("main线程"+i);
        }
    }
}

2020-03-17_120306.png

观测线程状态

线程的状态

  • NEW 未启动的线程
  • RUNNABLE 正在执行的线程
  • BLOCKED 被阻塞等待监视器锁定的线程
  • WAITING 等待另外一个线程执行特定动作的线程
  • TIMED_WAITING 等待另一个线程执行动作达到指定执行时间的线程
  • TERMINATED 已经退出的线程
public class TestState {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(()->{
            for (int i = 1; i < 5; i++) {
                System.out.println("Thread running"+"+"+i);
                try {
                    Thread.sleep(100);
                } 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);  //RUNNABLE

        while (state != Thread.State.TERMINATED){
            Thread.sleep(100);
            state = thread.getState(); //更新线程状态
            System.out.println(state);
        }
    }
}

2020-03-17_144518.png

线程优先级

  • Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行
  • 线程的优先级用数字表示,范围从1~10

    • Thread.MIN_PRIORITY = 1
    • Thread.MAX_PRIORITY = 10
    • Thread.NORM_PRIORITY = 5
    • 优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用
  • 使用以下方式改变或获取优先级

    • getPriority() setPriority(int xxx)
public class TestPriority {
    public static void main(String[] args) {
        //主线程默认优先级
        System.out.println(Thread.currentThread().getName()+"===>"+Thread.currentThread().getPriority());
        MyPriority priority = new MyPriority();
        Thread thread1 = new Thread(priority);
        Thread thread2 = new Thread(priority);
        Thread thread3 = new Thread(priority);
        Thread thread4 = new Thread(priority);
        Thread thread5 = new Thread(priority);

        //先设置优先级再启动
        thread1.setPriority(Thread.NORM_PRIORITY);
        thread1.start();

        thread2.setPriority(Thread.MIN_PRIORITY);
        thread2.start();

        thread3.setPriority(Thread.MAX_PRIORITY);
        thread3.start();

        thread4.setPriority(2);
        thread4.start();

        thread5.setPriority(9);
        thread5.start();

    }

}

class MyPriority implements Runnable{

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

守护线程

  • 线程分为用户线程和守护线程
  • 虚拟机必须确保用户线程执行完毕
  • 虚拟机不用等待守护线程执行完毕
Thread thread = new Thread();
thread.setDaemon(true); //默认是false,表示用户线程,设置为true,表示为守护线程

线程同步机制

三大不安全小案例

买票小案例

public class UnSafeBuyTicket implements Runnable{
    public static void main(String[] args) {
        UnSafeBuyTicket un = new UnSafeBuyTicket();
        new Thread(un,"A").start();
        new Thread(un,"B").start();
        new Thread(un,"C").start();
    }
    //票的数量
    private int ticket = 10; 
    boolean flage = true; //外部停止方式
    @Override
    public void run() {
        while (flage){ //买票
            byTicket();
        }
    }
    public void byTicket(){
        if(ticket<=0){
            flage = false;
            return;
        }
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"买到了第"+ticket--+"张票");
    }

}

模拟银行取钱小案例

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 money;  //余额
     String name; //持卡人

    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }
}
//模拟银行取钱
class Drawing extends Thread{
    Account account;  //账户
    private int drawingMoney;  //取了多少钱
    private int nowMoney; //现在手里有多少钱
    public Drawing(Account account,int drawingMoney,String name){
        super(name); //调用父类的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(2000);
        } 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);

    }
}

多线程操作ArrayList

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

同步方法

  • 同步方法:synchronized方法

    • 控制对象的访问,每一个对象对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞
    • 方法一旦执行,就独占该锁,直到方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行
    • 弊端:方法里面需要修改的内容才需要锁,锁的太多,浪费资源
  • 使用sychronized关键字让买票变的线程安全
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();
        //开启三个线程
        new Thread(buyTicket, "A同学").start();
        new Thread(buyTicket, "B同学").start();
        new Thread(buyTicket, "C同学").start();

    }

}

class BuyTicket implements Runnable {
    //票的数量
    private int TicketNum = 20;
    //停止售票的标识位
    private boolean flage = true;

    @Override
    public void run() {
        while (flage) {
            try {
                //买票
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    //synchronized方法,锁的当前对象本身,this
    
    private synchronized void buy() throws InterruptedException {
        if (TicketNum <= 0) {
            flage = false;
            return;
        }
        Thread.sleep(100);
        System.out.println(Thread.currentThread().getName() + "买到第" + TicketNum-- + "张票");
    }

}

同步代码块

  • 同步代码块:synchronized(Obj){}

    • Obj称为同步监视器,可以是任何对象,推荐使用共享资源作为同步监视器
    • 锁的对象就是变化的量,需要增删改的对象
    • 同步方法的同步监视器就是this,即对象本身
  • 使用sychronized代码块让取钱变的线程安全
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 money;  //余额
     String name; //持卡人

    public Account(int money, String name) {
        this.money = money;
        this.name = name;
    }
}
//模拟银行取钱
class Drawing extends Thread{
    Account account;  //账户
    private int drawingMoney;  //取了多少钱
    private int nowMoney; //现在手里有多少钱
    public Drawing(Account account,int drawingMoney,String name){
        super(name); //调用父类的name,线程的名字
        this.account = account;
        this.drawingMoney = drawingMoney;
    }
    @Override
    public void run() {
        //synchronized同步块,锁的对象是变化的量,是需要增删改的量
       synchronized(account){
           //判断有没有钱
           if(account.money - drawingMoney < 0){
               System.out.println(Thread.currentThread().getName()+"钱不够,取不了!");
               return;
           }
           //模拟延时
           try {
               Thread.sleep(2000);
           } 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);
       }

    }
}
  • 使用sychronized代码块让ArrayList变成线程安全的
public class UnsafeList {
    public static void main(String[] args) {
        ArrayList list = new ArrayList();
        for (int i = 0; i < 10000; i++) {
            new Thread(()->{
                //synchronized锁的是变化的量
               synchronized (list){
                   list.add(Thread.currentThread().getName());
               }
            }).start();
        }
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(list.size());
    }
}

CopyOnWriteArrayList

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

    //化妆,互相持有对方的锁,就是需要拿到对方的资源
    public 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 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();
        }
    }

    //化妆,互相持有对方的锁,就是需要拿到对方的资源
    public 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锁

  • 使用Lock对象来显式定义同步锁对象来实现同步
  • 比较常用的是ReentrantLock,可以显式加锁、释放锁

synchronized和Lock的区别?

  • Synchronized 内置的Java关键字, Lock 是一个Java类
  • Synchronized 无法判断获取锁的状态,Lock 可以判断是否获取到了锁
  • Synchronized 是隐式锁,出了作用域自动释放;Lock是显式锁,需要手动开启和释放锁.如果不释放锁,就会出现死锁!
  • Synchronized 线程 1(获得锁->阻塞)、线程2(等待->傻傻的等);Lock锁就不一定会等待下去;
  • Synchronized 可重入锁,不可以中断的,非公平;Lock ,可重入锁,可以 判断锁,非公平(可以自己设置);
  • Synchronized 适合锁少量的代码同步问题,Lock 适合锁大量的同步代码!

    • Lock是显式锁(手动开启和关闭锁),synchronized是隐式锁,出了作用域自动释放
    • Lock只有代码块锁,synchronized有代码块锁和方法锁
public class TestLock {
    public static void main(String[] args) {
        TestLock2 lock = new TestLock2();
        new Thread(lock,"Thread-1").start();
        new Thread(lock,"Thread-2").start();
        new Thread(lock,"Thread-3").start();
    }

}
class TestLock2 implements Runnable{
    int ticketNums = 10;
    private static 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();//释放锁
            }
        }
    }
}

线程通信问题

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

sleep和wait的区别?

  • 来自不同的类

    • wait来自Object类
    • sleep来自Thread类
  • 锁的释放不同

    • wait会释放锁
    • sleep抱着锁睡觉,不会释放锁
  • 使用的范围不同

    • sleep可以作用在任何地方
    • wait必须作用在同步代码块中
  • 是否需要捕获异常不同

    • sleep必须捕获异常
    • wait不需要捕获异常

生产者和消费者问题

管程法
//生产者消费者模型,使用缓冲区解决-管程法
public class TestPC {
    public static void main(String[] args) {
        SynContainer synContainer = new SynContainer();
        new Productor(synContainer).start();
        new Consumer(synContainer).start();
    }
}
//生产者
class Productor extends Thread{
    SynContainer synContainer;
    public Productor(SynContainer synContainer){
        this.synContainer = synContainer;
    }
    //生产
    @Override
    public void run() {
        for (int i = 1; i <30; i++) {
            System.out.println("生产了第"+i+"只鸡");
            try {
                Thread.sleep(500);  //假设生产比消费的速度快
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synContainer.push(new Chicken(i));

        }
    }
}
//消费者
class Consumer extends Thread{
    SynContainer synContainer;
    public Consumer(SynContainer synContainer){
        this.synContainer = synContainer;
    }
    //消费
    @Override
    public void run() {
        for (int i = 1; i <30; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("消费了第==>"+synContainer.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-1){
            //通知消费者消费,生产者等待
            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;
    }

}
信号灯法
//生产者和消费者问题,使用信号灯法,利用标志位解决
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++) {
            this.tv.watch();
        }
    }
}
class TV{
    //演员表演,观众等待   false
    //观众观看,演员等待   true
    String voice;
    boolean flage = true;
    //表演
    public synchronized void play(String voice){
        if(!flage){
            try {
                this.wait(); //等待表演
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("演员表演了:"+voice);
        //通知观众观看
        this.notifyAll(); //通知唤醒
        this.voice = voice;
        this.flage = !this.flage;
    }
    //观看
    public synchronized void watch(){
        if(flage){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("观众观看了:"+voice);
        this.notifyAll();  //通知唤醒
        this.flage = !this.flage;
    }
}

线程池

  • 背景

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

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

    • 提高响应速度(减少了创建新线程的时间)
    • 降低资源消耗(重复利用线程池中的线程,不需要每次都创建)
    • 便于线程管理
  • 线程池相关API:ExecutorService 和Executor

    • ExecutorService:真正的线程池接口
      常见子类ThreadPoolExecutor

      • void execute(Runnable command):执行任务,没有返回值,一般用来执行Runnable
      • <T> Future<T> submit(Callable<T> task):执行任务,有返回值,一般用来执行Callable
      • void shutdown():关闭连接池
    • Executor:工具类、线程池的工厂类,用于创建并返回不同类型的线程池
public class TestPool1 {
    public static void main(String[] args) {
        //创建服务,创建线程池,池中创建了5个线程
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        //执行,使用了3个线程
        executorService.execute(new MyThread());
        executorService.execute(new MyThread());
        executorService.execute(new MyThread());
        //关闭连接
        executorService.shutdown();

    }
}
class MyThread implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}
public class TestPool2 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //创建服务,创建线程池,池中创建5个线程
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        //执行服务
        executorService.submit(new MyThread());
        executorService.submit(new MyThread());
        Future<Boolean> future = executorService.submit(new MyThread());
        //得到Callable的返回值
        Boolean b = future.get();
        System.out.println(b);
        //关闭连接
        executorService.shutdown();
    }
}
class MyThread implements Callable<Boolean>{

    @Override
    public Boolean call() throws Exception {
        System.out.println(Thread.currentThread().getName());
        return false;
    }
}

踏雪无痕恋
0 声望0 粉丝

Java开发 Linux运维