线程优先级;守护线程;线程同步(synchronized);死锁;Lock;管程法;线程池

线程优先级

优先级高,只是意味着获得调度的概率高,并不是一定首先被CPU调度

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

        //先设置优先级,再启动
        t1.start();   //默认为5;

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

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

        t4.setPriority(Thread.MAX_PRIORITY);  //虽然优先级最高但不一定优先执行
        t4.start();
    }
}
class MyPriority implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
    }
}

守护线程(daemon)

  • 线程分为用户线程和守护线程
  • 虚拟机必须确保用户线程执行完毕
  • 虚拟机不用等待守护线程执行完毕,如后台记录操作日志,垃圾回收线程(gc),监控内存
public class TestDaemon {
    public static void main(String[] args) {
        
    
     God god=new God();
     Ou ou =new Ou();
     Thread thread = new Thread(god);
        
     thread.setDaemon(true);
    
     thread.start();
     
     new Thread(ou).start();

}}
//上帝
class God implements Runnable{

    @Override
    public void run() {
        while (true){
            System.out.println("守护");
        }
    }
}
//你
class Ou implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 36500; i++) {
            System.out.println("快乐活着");
        }
        System.out.println("goodbye");
    }
}

线程同步

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

当并发时如果某些线程想修改这个对象,就需要线程同步,这其实就是一种等待机制,这些线程需要进入这个对象的等待池形成队列,前面线程使用完毕,下一个线程再使用。

线程同步的形成条件:队列+锁

锁机制(synchronized)每一个对象都有一把锁,synchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,后面被阻塞的线程才能获得这个锁,继续执行。

缺陷:若将一个大的方法申明为synchronized将会影响效率。
方法里面需要修改的内容才需要锁,锁的太多,浪费资源。

加上synchronized这个关键字就会变成同步方法。

synchronized默认锁的是this. 就是这个对象本身,或者是这个方法本身的类

有两种形式:
1. synchronized同步方法,锁的是这个方法本身的类
2. synchronized同步块,可以锁任何对象,锁的对象是变化的量,就是增删改的对象。比如锁银行这个类没用,所以不能用同步方法,要用同步块锁账户。

买票这个例子要锁买票这个方法。也就是买票这个类。所以可以直接用同步方法(用关键字直接修饰方法即可):
private synchronized void buy() throws InterruptedException {
}

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 synchronized void buy() throws InterruptedException {
       //判断是否有票
       if(ticketNums<=0){
           flag=false;
           return;
       }
       Thread.sleep(100);
       System.out.println(Thread.currentThread().getName()+"拿到了"+ticketNums--);
   }
}

银行取钱这个例子如果对run这个方法用synchronized锁的是这个类,也就是Drawing,锁的是银行,但银行是不变的,应该锁账户,所以应该用同步块,锁用户,而不是同步方法。
直接用synchronized(account){run方法的内容}

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,"女朋友");

        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;
    //取了多少钱
    int drawingMoney;
    //现在有多少钱
    int nowMoney;
    public Drawing(Account account,int drawingMoney,String name){
      super(name);
        this.account=account;
        this.drawingMoney=drawingMoney;
    }
    //取钱

    @Override
    public void run() {
        synchronized (account){
            //判断有没有钱
            if(account.money-drawingMoney<0){
                System.out.println(Thread.currentThread().getName()+"钱不够,取不了");
                return;
            }
            //卡内的钱
            account.money = account.money-drawingMoney;
            //你手里的钱
            nowMoney=nowMoney+drawingMoney;
            System.out.println(account.name+"余额为:"+account.money);
            System.out.println(this.getName()+"手里的钱:"+nowMoney);
        }
    }
}

死锁

死锁:多个线程互相抱着对方需要的资源,然后形成僵持。
导致两个或者多个线程都在等待对方释放资源,都会停止执行的情况,某一个同步快同时拥有“两个以上对象的锁”时,就可能会发生“死锁”的情况

例子:

public class DeakLock {
    public static void main(String[] args) {
        Makeup g1=new Makeup(0,"小红");
        Makeup g2=new Makeup(1,"小黑");

        g1.start();
        g2.start();
    }
}

//口红
class Lipstick{

}

//镜子
class Mirror {

}

class Makeup extends Thread{

    //需要的资源只有一份,用static来保证一份
    static Lipstick lipstick = new Lipstick();
    static Mirror mirror = new Mirror();

    int choice ;//选择
    String girlName;
    Makeup (int choice,String girlName){
        this.choice=choice;
        this.girlName=girlName;
    }
    @Override
    public void run() {

        //化妆
        try {
            makeup();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
    //化妆,互相持有对方的锁,就是需要拿到对方的资源
    private void makeup() throws InterruptedException {
        if(choice == 0){
            synchronized (lipstick){//获得口红的锁
                System.out.println(this.girlName+"获得口红的锁");
                Thread.sleep(1000);
                synchronized (mirror){//一秒钟后获得镜子
                    System.out.println(this.girlName+"获得镜子的锁");
                }
            }

        }else{
            synchronized (mirror){//获得镜子的锁
                System.out.println(this.girlName+"获得镜子的锁");
                Thread.sleep(2000);
                synchronized (lipstick){//两秒钟后获得口红
                    System.out.println(this.girlName+"获得口红的锁");
                }
            }
        }
    }
}

在这里插入图片描述
输出结果不对,只需将锁拿出来即可,不能报对方的锁

//化妆,互相持有对方的锁,就是需要拿到对方的资源
    private void makeup() throws InterruptedException {
        if(choice == 0){
            synchronized (lipstick){//获得口红的锁
                System.out.println(this.girlName+"获得口红的锁");
                Thread.sleep(1000);
            }
            synchronized (mirror){//一秒钟后获得镜子
                System.out.println(this.girlName+"获得镜子的锁");
            }

        }else{
            synchronized (mirror){//获得镜子的锁
                System.out.println(this.girlName+"获得镜子的锁");
                Thread.sleep(2000);
            }
            synchronized (lipstick){//两秒钟后获得口红
                System.out.println(this.girlName+"获得口红的锁");
            }
        }
    }

在这里插入图片描述

Lock(锁)

ReentrantLock(可重入锁)类实现了Lock
对比:

  • Lock锁是显式锁(手动开启,关闭),synchronized是隐式锁,出了作用域自动释放
  • Lock只有代码块锁,synchronized有代码块锁和方法锁
  • 使用Lock锁,JVM将花费较少时间来调度线程,性能更好。并且具有更好的扩展性(提供更多的子类)
    在这里插入图片描述

生产者/消费者模式->管程法

//测试:生产者消费者模型-->利用缓冲区解决:管程法
//生产者,消费者,产品。缓冲区
public class TestPC {
    public static void main(String[] args) {
        SynContainer container = new SynContainer();
        new Producter(container).start();
        new Consumer(container).start();
    }
}

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

    public Producter(SynContainer container){
        this.container=container;
    }
//生产
    @Override
    public void run() {
        for (int i = 0; i < 100; 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 = 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;

    //生产者放入产品
    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;
    }
}

线程池

经常创建和销毁、使用特别大的资源,比如并发情况下的线程,对性能影响很大,提前创建好多个线程,放入线程池冲,使用时直接获取,使用完放回池中。可以避免频繁创建销毁、实现重复利用。类似生活中的公共交通工具

//测试线程池
public class TestPool {
    public static void main(String[] args) {


        //创建服务,创建线程池  newFixedThreadPool参数为线程池的大小
        // ExecutorService是真正的线程池接口,需要通过Executors创建线程池的大小
        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());
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值