Java-多线程

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

多线程方法:

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

Thread(多线程同时下载文件)

推荐使用Runnable

(需要commons-io包)

import org.apache.commons.io.FileUtils;

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

//练习Thread,实现多线程同步下载图片
public class TestThread2 extends Thread{
    private String url;//下载连接
    private String name;//文件名

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

    //线程执行体
    @Override
    public void run() {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downLoader(url,name);
        System.out.println("文件:"+name+",下载完成");
    }

    public static void main(String[] args) {
        TestThread2 t1 = new TestThread2("https://commons.apache.org/proper/commons-io/images/commons-logo.png", "1.png");
        TestThread2 t2 = new TestThread2("https://fanyi-cdn.cdn.bcebos.com/static/translation/img/header/logo_e835568.png", "百度翻译2.png");
        TestThread2 t3 = new TestThread2("https://commons.apache.org/proper/commons-io/images/io-logo-white.png", "3.png");
        t1.start();
        t2.start();
        t3.start();
    }
}

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

Runnable

//创建线程方式2:实现Runnable接口,重写run方法,执行线程都如runnable接口实现类,调用start方法。
public class TestThread3 implements Runnable {
    private String url;//下载连接
    private String name;//文件名

    public TestThread3(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) {
        TestThread3 t1 = new TestThread3("https://commons.apache.org/proper/commons-io/images/commons-logo.png", "Apache.png");
        TestThread3 t2 = new TestThread3("https://fanyi-cdn.cdn.bcebos.com/static/translation/img/header/logo_e835568.png", "百度翻译.png");
        TestThread3 t3 = new TestThread3("https://commons.apache.org/proper/commons-io/images/io-logo-white.png", "commons.png");
        new Thread(t1).start();
        new Thread(t2).start();
        new Thread(t3).start();
    }
}

并发问题

龟兔赛跑:

//模拟龟兔赛跑
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+"步");
        }
    }

    //判断比赛是否完成
    public boolean gameOver(int steps){
        //判断是否有胜利者
        if (winner!=null) {
            return true;//已经有胜利者了
        }{
            if (steps==100){
                winner=Thread.currentThread().getName();
                System.out.println("winner is "+winner);
                return true;
            }
        }
        return false;
    }

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

Callable

import org.apache.commons.io.FileUtils;

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

//线程创建方式3:实现Callable接口
/*
Callable优点:
1、可以定义返回值
2、可以抛出异常
*/
public class TestCallable implements Callable<Boolean> {
    private String url;//下载连接
    private String name;//文件名

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

    //线程执行体
    @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://commons.apache.org/proper/commons-io/images/commons-logo.png", "1.png");
        TestCallable t2 = new TestCallable("https://fanyi-cdn.cdn.bcebos.com/static/translation/img/header/logo_e835568.png", "百度翻译2.png");
        TestCallable t3 = new TestCallable("https://commons.apache.org/proper/commons-io/images/io-logo-white.png", "3.png");

        //创建服务:
        ExecutorService ser = Executors.newFixedThreadPool(3);
        //开启服务:
        Future<Boolean> r1 = ser.submit(t1);
        Future<Boolean> r2 = ser.submit(t2);
        Future<Boolean> r3 = ser.submit(t3);
        //获取结果:
        Boolean rs1 = r1.get();
        Boolean rs2 = r2.get();
        Boolean rs3 = r3.get();
        //关闭服务:
        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方法出现问题");
        }
    }
}

静态代理模式

//静态代理
/*
    总结:
    1、真实对象和代理对象必须要实现同一个接口
    2、代理对象要代理真实对象
    好处:
    1、代理对象可以做很多真实对象做不了的事情
    2、真实对象做自己的事情
 */
public class StaticProxy {
    public static void main(String[] args) {
        You you = new You();
        new Thread(()-> System.out.println("I love you")).start();
        new WeddingCompany(new You()).happyMarry();

//        WeddingCompany weddingCompany = new WeddingCompany(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 after() {
        System.out.println("结婚之后收尾款");

    }

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

lambda表达式

无参:

/*
Lambda表达式推导
 */
public class TestLambda1 {
    //3、静态内部类
    static class Like2 implements ILike{
        @Override
        public void Lambda() {
            System.out.println("I like 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("I like lambda3");
            }
        }
        like = new Like3();
        like.Lambda();

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

        //6、用Lambda表达式简化
        like = ()->{
            System.out.println("I like lambda5");
        };
        like.Lambda();

    }
}
//1、定义了一个函数式接口(只有一个方法的接口就是函数式接口)
interface ILike{
    void Lambda();
}

//2、实现类
class Like implements ILike{
    @Override
    public void Lambda() {
        System.out.println("I like lambda");
    }
}

有参:

/*
                    JDK8新增特性
    总结:
        lambda表达式只能有一行的s情况下,才能简化为一行,否则就要用代码块(花括号)包裹
        使用lambda表达式的前提接口为函数式接口(只有一个方法)
        多个参数也可以去掉类型,但是必须由括号包裹,只有一个参数时可以不加括号
 */
public class TestLambda2 {
    static class Love2 implements ILove{
        @Override
        public void love(int a) {
            System.out.println("I love you "+a);
        }
    }

    public static void main(String[] args) {
        ILove love = new Love();
        love.love(1);

        love = new Love2();
        love.love(2);

        class Love3 implements ILove{
            @Override
            public void love(int a) {
                System.out.println("I love you "+a);
            }
        }
        love = new Love3();
        love.love(3);

        love = new ILove() {
            @Override
            public void love(int a) {
                System.out.println("I love you "+a);
            }
        };
        love.love(4);
        
        /*//lambda表示简化
        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);};*/
        //简化花括号
        love = a-> System.out.println("I love you " + a);

        love.love(5);
    }
}

interface ILove{
    void love(int a);
}

class Love implements ILove{
    @Override
    public void love(int a) {
        System.out.println("I love you "+a);
    }
}

线程停止

不推荐强行停止线程,推荐用合理的方法让线程自己停止。

//测试stop
public class TestStop implements Runnable{

    //设置一个标志位
    private Boolean flag=true;
    private int i=0;

    @Override
    public void run() {
        while(flag){
            System.out.println("Run...Thread"+i++);
        }
    }

    //设置一种公开的方法,停止线程
    public void stop(){
        this.flag=false;
    }

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

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

线程休眠

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

网络延时      

//模拟网络延时:放大问题的发生性
public class TestSleep 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) {
        TestSleep testSleep = new TestSleep();

        new Thread(testSleep,"小明").start();
        new Thread(testSleep,"黄牛").start();
        new Thread(testSleep,"老师").start();

    }
}

倒计时

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

//模拟倒计时
public class TestSleep2 {

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

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

线程礼让

  • 让当前正在执行的线程暂停,但是不阻塞。
  • 将线程从运行状态重新转换为就绪状态。
  • 让CPU重新调度,礼让不一定成功。
//测试线程礼让
//礼让不一定成功,看CPU调度。
public class TestYield {
    public static void main(String[] args) {
        MyYield myYield1 = new MyYield();

        new Thread(myYield1,"a").start();
        new Thread(myYield1,"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

//线程合并,好比插队,join之后会先执行join线程再正常执行
public class TestJoin implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("join线程-->"+i);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        //新建对象,启动线程
        TestJoin join = new TestJoin();
        Thread thread = new Thread(join);
        thread.start();

        for (int i = 0; i < 1000; i++) {
            if (i==50) 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);
                    System.out.println("........");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

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

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

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

线程优先级

  • 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 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();
        //t1.setPriority(Thread.MIN_PRIORITY);

        t2.setPriority(2);
        t2.start();

        t3.setPriority(Thread.NORM_PRIORITY);
        t3.start();

        t4.setPriority(6);
        t4.start();

        t5.setPriority(8);
        t5.start();

        t6.setPriority(Thread.MAX_PRIORITY);
        t6.start();
    }
}
class MyPriority implements Runnable{

    @Override
    public void run() {
        //展示线程名称和优先级
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
    }
}

守护线程

守护线程不会被虚拟机确保一直执行。

用户线程会被虚拟机确保执行完毕。

线程默认为用户线程。

方法:setDaemon();

案例:

//测试线程守护
//愿风神忽悠你
public class TestDaemon {
    public static void main(String[] args) {
        Wind wind = new Wind();
        You you = new You();

        Thread thread = new Thread(wind);
        thread.setDaemon(true);//  线程默认为用户线程(false),可以设置为守护线程(true)。
        thread.start();

        new Thread(you).start();//ni(用户线程)启动了。。。
    }
}

//上帝
class Wind implements Runnable{

    @Override
    public void run() {
        while (true){
            System.out.println("愿风神忽悠你");
        }
    }
}

//你
class You implements Runnable{

    @Override
    public void run() {
        for (int i = 1; i <= 36500; i++) {
            System.out.println("你开心的第"+ i +"天");
        }
        System.out.println("Goodbye");
    }
}

线程同步

解决并发问题,使用线程同步(队列+锁)

三大不安全案例

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;
    private boolean flag = true;
    
    @Override
    public void run() {
        //买票
        while (flag == true){
            buy();
        }
    }

    public void buy(){
        if (ticketNums <= 0){
            flag = false;
            return;
        }
        try {
            Thread.sleep(100);
            System.out.println(Thread.currentThread().getName() + "买到了第" + ticketNums-- +"张票");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

2、取钱

//不安全的取钱
//两个人去银行取钱
public class UnsafeBank {
    public static void main(String[] args) {
        Account vip = new Account(500, "VIP");
        Drawing drawing1 = new Drawing(vip, 300, "小明");
        Drawing drawing2 = new Drawing(vip, 500, "小红");
        drawing1.start();
        drawing2.start();
    }
}

//账户
class Account{
    private int money;
    private String name;
    public Account(int money,String name){
        this.money = money;
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }
}

//取钱
class Drawing extends Thread{
    //账户
    Account account;
    //取了多少钱
    int drawingMoney;
    //现在手里有多少钱
    String name;

    public Drawing(Account account,int drawingMoney,String name){
        this.name = name;
        this.account = account;
        this.drawingMoney = drawingMoney;

    }

    @Override
    public void run() {
        try {
            drawing();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //取钱
    public void drawing() throws InterruptedException {
        //Thread.sleep(200);
        if (account.getMoney()-drawingMoney<0){
            System.out.println(name+"卡里面钱不够了");
            return;
        }
        System.out.println(name+"取出:"+drawingMoney+"元");
        account.setMoney(account.getMoney()-drawingMoney);
        System.out.println(name+"卡余额还有:"+account.getMoney());
        System.out.println(name+"目前手中有:"+drawingMoney+"元");

    }
}

3、不安全的集合

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

//不安全的集合 
public class UnsafeList {
    public static void main(String[] args) throws InterruptedException {
        List<String> list = new ArrayList();
        for (int i = 1; i <= 10000; i++) {
            new Thread(()->list.add(Thread.currentThread().getName())).start();
        }
        Thread.sleep(5000);
        System.out.println(list.size());
    }
}

线程同步(解决线程不安全问题)

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;
    private boolean flag = true;

    @Override
    public void run() {
        //买票
        while (flag == true){

            try {
                buy();
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public synchronized void buy() throws InterruptedException {
        if (ticketNums <= 0){
            flag = false;
            return;
        }

        Thread.sleep(100);
        System.out.println(Thread.currentThread().getName() + "买到了第" + ticketNums-- +"张票");

    }
}

2、取钱

//不安全的取钱
//两个人去银行取钱
public class UnsafeBank {
    public static void main(String[] args) {
        Account vip = new Account(5000, "VIP");
        Drawing drawing1 = new Drawing(vip, 300, "小明");
        Drawing drawing2 = new Drawing(vip, 500, "小红");
        drawing1.start();
        drawing2.start();
    }
}

//账户
class Account{
    private int money;
    private String name;
    public Account(int money,String name){
        this.money = money;
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getMoney() {
        return money;
    }

    public void setMoney(int money) {
        this.money = money;
    }
}

//取钱
class Drawing extends Thread{
    //账户
    Account account;
    //取了多少钱
    int drawingMoney;
    //现在手里有多少钱
    String name;

    public Drawing(Account account,int drawingMoney,String name){
        this.name = name;
        this.account = account;
        this.drawingMoney = drawingMoney;
    }

    @Override
    public void run() {
        //synchronized默认锁的是this,
        //可以用synchronized块锁需要增删改的对象。
        synchronized (account){
            try {
                drawing();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //取钱
    public void drawing() throws InterruptedException {
        //Thread.sleep(200);
        if (account.getMoney()-drawingMoney<0){
            System.out.println(name+"卡里面钱不够了");
            return;
        }
        System.out.println(name+"取出:"+drawingMoney+"元");
        account.setMoney(account.getMoney()-drawingMoney);
        System.out.println(name+"卡余额还有:"+account.getMoney());
        System.out.println(name+"目前手中有:"+drawingMoney+"元");
    }
}

3、arrayList

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

//不安全的集合
public class UnsafeList {
    //arraylist是不安全的集合,可以用synchronized锁住需要更新的对象。
    public static void main(String[] args) throws InterruptedException {
        List<String> list = new ArrayList();
        for (int i = 1; i <= 10000; i++) {
            new Thread(()->{
                synchronized(list){
                    list.add(Thread.currentThread().getName());
                }
            }).start();
        }
        Thread.sleep(5000);
        System.out.println(list.size());
    }
}

JUC包下的安全的集合(CopyOnWriteArrayList)

import java.util.concurrent.CopyOnWriteArrayList;

//测试JUC下安全的集合(CopyOnWriteArrayList)
public class RestJUC {
    public static void main(String[] args) throws InterruptedException {
        CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();

        for (int i = 1; i <= 10000; i++) {
            new Thread(()->{
                list.add(Thread.currentThread().getName());
            }).start();
        }
        Thread.sleep(300);
        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 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();
        }
    }

    //化妆,互相持有对方的锁,构成线程死锁。
    public void makeup() throws InterruptedException {
        if (choice==0){
            synchronized(lipstick){
                System.out.println(this.name+"获得了口红");
                Thread.sleep(1000);
            }
            synchronized (mirror){
                System.out.println(this.name+"获得了镜子");
            }
        }else {
            synchronized (mirror){
                System.out.println(this.name+"获得了镜子");
                Thread.sleep(2000);
            }
        }
    }
}

达成死锁的四个必要条件:(只要阻止其中一个,就可以解开死锁)

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

ReentrantLock(可重用锁)

是显示锁,只有代码块锁,

JVM花费时间更少,性能更好。且具有更好的扩展性。

使用顺序:

        Lock>同步代码块(已经进入了相应的方法体,分配了相应的资源)>同步方法(在方法体之外)

import java.util.concurrent.locks.ReentrantLock;

//Lock锁
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 ticketNums = 10;
    //定义lock锁
    ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true){
            try {
                lock.lock();//加锁
                if (ticketNums>=0){
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(ticketNums--);
                }else break;
            }finally {
                lock.unlock();//解锁
            }
        }
    }
}

线程通信

生产者消费者问题(管城法)

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

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

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

    //生产
    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            container.push(new Product(i));
            System.out.println("生产了第"+i+"只鸡");
        }
    }
}
//消费者
class Consumer extends Thread{
    SynContainer container;

    public Consumer(SynContainer container) {
        this.container = container;
    }
    //消费
    //生产
    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            System.out.println("消费了第"+container.pop().id+"只鸡");
        }
    }
}
//产品
class Product{
    int id;

    public Product(int id) {
        this.id = id;
    }
}
//缓冲区
class SynContainer{
    //需要一个容器
    Product[] products = new Product[10];
    int count=0;

    //生产者生产产品
    public synchronized void push(Product product){
        //如果容器满了提醒消费者消费
        while(count == this.products.length){
            //提醒消费者消费
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果容器没满生产产品
        products[count] = product;
        count++;
        //可以通知消费者消费了
        this.notifyAll();
    }

    //消费者消费产品
    public synchronized Product pop(){
        //如果容器空了提醒生产者生产产品
        while (count==0){
            //等待生产者生产产品
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果容器没空消费产品
        count--;
        Product product = products[count];
        this.notifyAll();
        return product;
    }
}

生产者消费者问题(信号灯法)

//生产者消费者问题2:信号灯法。
//表演
public class TestPC2 {
    public static void main(String[] args) {
        TV tv = new TV();
        new Player(tv).start();
        new Watch(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 Watch extends Thread{
    TV tv;
    public Watch(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            this.tv.watch();
        }
    }
}
//表演
class TV{
     String voice;//节目
     boolean flag = true;  //为T演员表演,为F观众观看

    //演员表演
    public synchronized void play(String voice){
        if (!flag){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("演员表演了"+voice);
        notifyAll();
        this.voice = voice;
        this.flag = !this.flag;
    }
    //观众观看
    public synchronized void watch(){
        if (flag){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("观众观看了"+voice);
        notifyAll();
        flag = !this.flag;
    }
}

 线程池

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

public class TestPool {
    public static void main(String[] args) {
        //创建线程池
        ExecutorService service = Executors.newFixedThreadPool(2);
        //添加线程
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        //关闭线程池
        service.shutdown();
    }
}

class MyThread implements Runnable{

    @Override
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        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) throws ExecutionException, InterruptedException {
        new MyThread1().start();

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

        MyThread3 thread3 = new MyThread3();
        FutureTask futureTask = new FutureTask<Integer>(thread3);
        new Thread(futureTask).start();
        Object o = futureTask.get();
        System.out.println(o);
    }
}
//继承Thread类
class MyThread1 extends Thread{
    @Override
    public void run() {
        System.out.println("Thread");
    }
}
//实现Runnable接口
class MyThread2 implements Runnable{

    @Override
    public void run() {
        System.out.println("Runnable");
    }
}
//实现Callable接口
class MyThread3 implements Callable<Integer>{

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值