Day16

本文介绍了Java中线程的状态观测、线程优先级、守护线程、线程同步以及并发问题的解决方案,包括死锁、锁机制、线程池和生产者消费者模式。通过实例展示了如何避免线程不安全,以及使用JUC(Java并发工具包)提高并发性能。
摘要由CSDN通过智能技术生成

线程状态观测

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-o77cBFa2-1613899142582)(D:\date img\QQ截图20210220082747.png)]

package com.duoXianCheng.stop;
/*
    观察测试线程的状态
 */
public class TextState {

    public static void main(String[] args) {
        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);

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

        while (state!=Thread.State.TERMINATED){//如果线程不停止就一直输出状态
            state=thread.getState();
            System.out.println(state);//更新状态
        }
        //一旦线程结束就不能在重新启动
        //  thread.start();
    }
}

线程优先级

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-14p0vFse-1613899142584)(D:\date img\QQ截图20210220084538.png)]

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

package com.duoXianCheng.stop;
/*
    线程优先级
 */
public class TextPriority {
    public static void main(String[] args) {
        //主线程默认优先级
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());

        MyPriority myPriority = new MyPriority();
        Thread thread1 = new Thread(myPriority);
        Thread thread2 = new Thread(myPriority);
        Thread thread3 = new Thread(myPriority);
        Thread thread4 = new Thread(myPriority);
        Thread thread5 = new Thread(myPriority);
        Thread thread6 = new Thread(myPriority);

        thread1.start();
        thread2.setPriority(9);//设置优先级   优先级高不一定先执行,需要看CPU调度
        thread2.start();
        thread3.setPriority(3);
        thread3.start();
        thread4.setPriority(7);
        thread4.start();
        thread5.setPriority(1);
        thread5.start();
        thread6.setPriority(Thread.MAX_PRIORITY);
        thread6.start();

    }
}
class MyPriority implements Runnable{
    @Override
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
    }
}

守护线程

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rVEJBgN5-1613899142586)(D:\date img\QQ截图20210220091125.png)]

package com.duoXianCheng.stop;
/*
    守护线程
        当线程结束后,守护线程之后也会结束
 */
public class TextDaemon {
    public static void main(String[] args) {
        You you = new You();
        God god = new God();
        Thread thread = new Thread(god);
        thread.setDaemon(true);
        thread.start();
        new Thread(you).start();
    }
}
class You implements Runnable{
    @Override
    public void run() {
        for (int i = 100; i >=0; i--) {
            System.out.println("you have"+i+"years");
        }
        System.out.println("good bye world");
    }
}
class God implements Runnable{
    @Override
    public void run() {
        while(true) {
            System.out.println("i am god daemon you");
        }
    }
}

线程同步

多个线程操作同一个资源

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xDzmvTRf-1613899142589)(D:\date img\QQ截图20210220095740.png)]

线程不安全案例一

package com.duoXianCheng.syn;
/*
    模拟不安全的买票
        会出现线程不安全的问题,出现负数票
 */
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();
        new Thread(buyTicket,"1").start();
        new Thread(buyTicket,"2").start();
        new Thread(buyTicket,"3").start();
    }
}
class BuyTicket implements Runnable{
    //需要定义有几张票
    private int ticket=10;
    //使用外部停止
    private boolean flg=true;
    @Override
    public void run() {
        while (flg){
            System.out.println(Thread.currentThread().getName()+"抢到了第"+ticket--+"张票");
            if (ticket<=0){
                flg=false;
            }
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    //

}

线程不安全案例二

package com.duoXianCheng.syn;
/*
    模拟银行取钱
   		取前为负数
 */
public class UnsafeBank {
    public static void main(String[] args) {
        Account account = new Account("account", 300);
        new Thread(new Bank(account,200,"you "),"you").start();
        new Thread(new Bank(account,300,"girlfriends "),"girlfriends").start();
    }
}
//账户
class Account{
   String name;
   int money;

    public Account(String name, int money) {
        this.name = name;
        this.money = money;
    }
}
//bank
class Bank extends Thread{
    Account account;
    private int quMoney;
    private int nowMoney;

    public Bank(Account account, int quMoney, String name) {
        super(name);
        this.account = account;
        this.quMoney = quMoney;


    }

    @Override
    public void run() {
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (account.money<quMoney){
            System.out.println(Thread.currentThread().getName()+"账户余额不足");
            return;
        }
        account.money=account.money-quMoney;
        nowMoney=nowMoney+quMoney;
        System.out.println(account.name+"的余额为"+account.money);
        System.out.println(Thread.currentThread().getName()+"取了"+quMoney+"现在有了"+nowMoney);
    }
}

线程不安全案例三

package com.duoXianCheng.syn;

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

/*
    线程不安全
    	导致线程丢失
 */
public class UnsafeList {
    public static void main(String[] args) {
        List<String> strings = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            new Thread(()->strings.add(Thread.currentThread().getName())).start();
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(strings.size());
    }
}

同步方法

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-duqWfast-1613899142590)(D:\date img\QQ截图20210220143905.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yfT6qmlt-1613899142591)(D:\date img\QQ截图20210220151629.png)]

package com.duoXianCheng.syn;
/*
    模拟不安全的买票
        会出现线程不安全的问题,出现负数票
 */
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();
        new Thread(buyTicket,"1").start();
        new Thread(buyTicket,"2").start();
        new Thread(buyTicket,"3").start();
    }
}
class BuyTicket implements Runnable{
    //需要定义有几张票
    private int ticket=10;
    //使用外部停止
     boolean flg=true;
    @Override
    public void run() {
        while (flg){

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

    }
    private synchronized void buy()  {//synchronized

        if (ticket<=0){
            flg=false;
            return;
        }

        System.out.println(Thread.currentThread().getName()+"抢到了第"+ticket--+"张票");
    }
    //

}
package com.duoXianCheng.syn;
/*
    模拟银行取钱

 */
public class UnsafeBank {
    public static void main(String[] args) {
        Account account = new Account("account", 300);
        new Thread(new Bank(account,200,"you "),"you").start();
        new Thread(new Bank(account,300,"girlfriends "),"girlfriends").start();
    }
}
//账户
class Account{
   String name;
   int money;

    public Account(String name, int money) {
        this.name = name;
        this.money = money;
    }
}
//bank
class  Bank extends Thread{
    Account account;
    private int quMoney;
    private int nowMoney;

    public Bank(Account account, int quMoney, String name) {
        super(name);
        this.account = account;
        this.quMoney = quMoney;


    }

    @Override
    public  void run() {
        synchronized (account){//同步监视器 监视的对象是需要增删改查的对象
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (account.money<quMoney){
                System.out.println(Thread.currentThread().getName()+"账户余额不足");
                return;
            }
            account.money=account.money-quMoney;
            nowMoney=nowMoney+quMoney;
            System.out.println(account.name+"的余额为"+account.money);
            System.out.println(Thread.currentThread().getName()+"取了"+quMoney+"现在有了"+nowMoney);
        }
        }

}
package com.duoXianCheng.syn;

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

/*
    线程不安全
 */
public class UnsafeList {
    public static void main(String[] args) {
        List<String> strings = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            synchronized (strings){//线程不安全的解决方法  监视的对象是需要增删改查的对象
                new Thread(()->strings.add(Thread.currentThread().getName())).start();
            }

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

JUC安全类的集合

package com.duoXianCheng.syn;

import java.util.concurrent.CopyOnWriteArrayList;

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

死锁

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-d141Wc3F-1613899142592)(D:\date img\QQ截图20210220153850.png)]

package com.duoXianCheng.syn;
/*
    测试死锁
 */
public class DeadLock {
    public static void main(String[] args) {
        Gir gir0 = new Gir("白雪公主", 0);
        Gir gir1 = new Gir("女巫", 1);
        new Thread(gir0).start();
        new Thread(gir1).start();
    }
}
class JinZi{

}
class KouKong{

}
class Gir extends Thread{
    static JinZi jinZi=new JinZi();//static是保证只有一个资源
    static KouKong kouKong=new KouKong();
    String name;
    int choice;
    Gir(String name,int choice){
        this.name=name;
        this.choice=choice;
    }

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

    private void huaZ() throws InterruptedException {
        if (choice==0){
            synchronized (jinZi){
                System.out.println(this.name+"拿到了镜子");
                Thread.sleep(1000);

            }
            synchronized (kouKong){
                System.out.println(this.name+"拿到了口红");//不能同时拿两把锁,否则就会发生锁死
            }
        }else {
            synchronized (kouKong){
                System.out.println(this.name+"拿到了口红");
                Thread.sleep(3000);

            }
            synchronized (jinZi){
                System.out.println(this.name+"拿到了镜子");
            }
        }
    }
}

Lock(锁)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tBmtTlsg-1613899142593)(D:\date img\QQ截图20210220161631.png)]

package com.duoXianCheng.syn;

import java.util.concurrent.locks.ReentrantLock;

import static java.lang.Thread.sleep;

/*
    测试lock锁
 */
public class TextLock {
    public static void main(String[] args) {
        BuyP buyP = new BuyP();
        new Thread(buyP,"我").start();
        new Thread(buyP,"你").start();
        new Thread(buyP,"他").start();
    }
}
class BuyP implements Runnable{
    ReentrantLock lock=new ReentrantLock();
   boolean flg=true;
    private int p=10;

    @Override
    public void run() {
        try {
            buy();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    private void buy() throws InterruptedException {
        try{
            lock.lock();//枷锁
            while (flg){
                Thread.sleep(1000);
                if (p<=0){
                    flg=false;
                }
                System.out.println(Thread.currentThread().getName()+"抢到了第"+p--+"张票");

            }
        }finally {
            lock.unlock();//解锁
        }

    }
}

ReentrantLock可重用锁

线程协作

生产者消费者模式(问题)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-w8l0nTJp-1613899142594)(D:\date img\QQ截图20210220170413.png)]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vlZVwJdi-1613899142594)(D:\date img\QQ截图20210220170810.png)]

管程法

package com.duoXianCheng.syn;

import java.util.ArrayList;

/*
    测试生产者消费者问题 ————》管程法
        当生产者生产了一只鸡的时候,就通知消费者来吃 ,等待消费者吃
        当消费吃完之后,通知生产者生产,等待生产者生产鸡
 */
public class TextPC {
    public static void main(String[] args) {
        SynContainer synContainer = new SynContainer();
        Producer producer = new Producer(synContainer);
        Consumer consumer = new Consumer(synContainer);
        producer.start();
        consumer.start();
    }
}
//生产者
class Producer extends Thread{
    SynContainer container;
    public Producer(SynContainer container){
        this.container=container;
    }

    @Override
    public void run() {
        for (int i = 1; i < 10; i++) {
            container.push(new Chicken(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 < 10; i++) {
            System.out.println("吃了"+container.pop().chickenId+"只鸡");

        }
    }
}
//产品
class Chicken{
    int chickenId;
    Chicken(int chickenId){
        this.chickenId=chickenId;
    }
}
//缓冲区(仓库)
class SynContainer{
    //需要一个容器存放鸡
    Chicken[] chickens=new Chicken[1];
    //需要一个计算器,来看容器里面是否有鸡
     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.notify();
    }
    //消费者消费鸡
    public synchronized Chicken pop(){
        if (count==0){
            //通知生产者
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        count--;
        Chicken chicken=chickens[count];
        this.notify();
        return chicken;

    }
}

信号灯

package com.duoXianCheng.syn;

import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;

/*
    测试生产者消费者为题————》信号灯法
 */
public class TextPC2 {
    public static void main(String[] args) {
        TV tv = new TV();
        new Player(tv).start();
        new Watcher(tv).start();
    }
}
//player
class Player extends Thread{
 TV tv;
 public Player(TV tv){
     this.tv=tv;
 }

    @Override
    public void run() {
        for (int i = 1; i < 10; i++) {
            if (i%5==0){
                this.tv.play("广告");
            }else {
                this.tv.play("爱情公寓");
            }


        }
    }
}
//watcher
class Watcher extends Thread{
    TV tv;
    public Watcher(TV tv){
        this.tv=tv;
    }

    @Override
    public void run() {
        for (int i = 1; i < 10; i++) {
            tv.watch();
        }
    }
}
//产品
class TV{
    //演员表演时,观众等待,表演完成时通知观众观看
    //观众观看时,演员等待,观看完成时通知演员表演
    boolean flg=true;//创建一个标志
    String name;

//表演方法
    public synchronized void play(String name){
        if (!flg){
            try {
                this.wait();//判断标志为假的时候就等待
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("表演了节目"+name);
        this.notifyAll();
        this.name=name;
        this.flg=!this.flg;



    }
    //观看方法
    public synchronized void watch(){
        if (flg){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("观看了"+name);
        this.notifyAll();
        this.flg=!this.flg;

    }

}

线程池

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-91soDGaB-1613899142595)(D:\date img\QQ截图20210220220549.png)]

package com.duoXianCheng.syn;



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

/*
    线程池
 */
public class TextPool {
    public static void main(String[] args) {
        //创建服务,创建线程池
        //newFixedThreadPool:参数为线程池的大小
        ExecutorService service= Executors.newFixedThreadPool(10);
        //执行
        service.execute(new A());
        service.execute(new A());
        service.execute(new A());
        service.execute(new A());//没有返回值
        service.submit(new A());//有返回值的
        //关闭连接
        service.shutdown();

    }
}
class A implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值