Java多线程04:线程优先级、守护线程和线程同步

Java多线程04:线程优先级、守护线程和线程同步

线程优先级

  • Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行
  • 线程的优先级用数字表示,范围从0~10
    • Thread.Min_PRIORITY = 1;
    • Thread.MAX_PRIORITY = 10;
    • Thread.NORM_PRIORITY = 5;
  • 使用以下方式改变或获取优先级
    • getPriority()、setPriority(int xxx)

实例:

package com.lurenj.thread;

public class TestPriority {

    public static void main(String[] args) {

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

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

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

        t4.setPriority(10);
        t4.start();

        t5.setPriority(3);
        t5.start();

        t6.setPriority(6);
        t6.start();
        //主线程默认优先级
        System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());

    }

}

class MyPriority implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());
    }
}

守护(daemon)线程

  • 线程分为用户线程守护线程
  • 虚拟机必须确保用户线程执行完毕
  • 虚拟机不用等待守护线程执行完毕,如:后台记录操作日志、监控内存、垃圾回收等

实例

package com.lurenj.thread;

public class TestDaemon {
    public static void main(String[] args) {
        God god = new God();
        You2 you2 = new You2();

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

        new Thread(you2).start();


    }
}



//God

class God implements Runnable{
    @Override
    public void run() {
        while (true){
            System.out.println("保佑着你~");
        }
    }
}


//你
class You2 implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 36500; i++) {
            System.out.println("一生都开心的活着~");
        }
        System.out.println("========goodbye!=========");
    }
}

线程同步机制

  • 并发:同一个对象被多个线程同时操作
  • 线程同步:处理多线程问题时,多个线程访问同一个对象(并发) ,并且某些线程还想修改这个对象,这时候我们就需要线程同步,线程同步其实就是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池 形成队列,等待前面线程使用完毕,下一个线程再使用。
  • 线程同步形成条件:队列+锁
    • 由于同一进程的多个线程共享同一块储存空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制(synchronized) ,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可
  • 线程同步存在的问题:
    • 一个线程持有锁会导致其他所有需要此锁的线程挂起;
    • 在多线程竞争下,加锁、释放锁会导致比较多的上下文切换和调度延迟,引起性能问题;
    • 如果一个优先级高的线程等待一个优先级低的线程释放锁会导致优先级倒置,引起性能问题;

三大不安全案例

案例一:买票不安全,会出现重复或-1

package com.lurenj.syn;

//不安全的买票
//线程不安全,有负数和重复购买
public class UnsafeTicket {
    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();

        new Thread(station,"kubi").start();
        new Thread(station,"niubi").start();
        new Thread(station,"huangniu").start();
    }

}

class BuyTicket implements Runnable{

    //车票
    private int ticketNums = 10;
    private boolean flag = true;//外部停止
    @Override
    public void run() {
        while (flag){
            buy();
        }

    }

    private void buy(){
        //判断是否有票
        if (ticketNums <= 0){
            flag = false;
            return;
        }
        //模拟延时
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //买票
        System.out.println(Thread.currentThread().getName() + "拿到了" + ticketNums--);
    }
}

案例二:数组不安全,输出错误

package com.lurenj.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());
    }
}

案例三:银行取钱不安全,出现负数或者取出总额大于存款

package com.lurenj.syn;

import com.lurenj.oop.demo05.A;

//不安全的取钱
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() {
        //判断是否有钱
        if (account.money - drawingMoney < 0){
            System.out.println(this.getName() + "钱不够,取不了");
            return;
        }

        //sleep可以放大问题的发生性
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        account.money = account.money - drawingMoney;
        nowMoney += drawingMoney;
        System.out.println(account.name + "余额为:" + account.money);
        //Thread.currentThread().getName() = this.getName(),因为该类继承了Thread类,getName是其中的方法
        System.out.println(this.getName() + "手里的钱" + nowMoney);
    }
}

同步方法

  • 由于我们可以通过private关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是synchronized关键字,它包括两种方法:synchronized方法和synchronized块。

    同步方法:public synchronized void method(int args){}

  • synchronized方法控制对”对象“的访问,每个对象对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行。

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

同步块

  • 同步块:synchronized(Obj){}
  • Obj称之为同步监视器
    • Obj可以是任何对象,但是推荐使用共享资源作为同步监视器
    • 同步方法无需指定同步监视器,因为同步方法的同步监视器就是this,就是这个对象本身,或者是class[反射中讲解]
  • 同步监视器的执行过程
    1. 第一个线程访问,锁定同步监视器,执行其中代码
    2. 第二个线程访问,发现同比福建神器别锁定,无法访问
    3. 第一个线程访问完毕,解锁同步监视器
    4. 第二个线程访问,发现同步监视器没有锁,然后锁定并访问

实例一:解决买票不安全

package com.lurenj.syn;

//不安全的买票
//线程不安全,有负数和重复购买
public class UnsafeTicket {
    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();

        new Thread(station,"kubi").start();
        new Thread(station,"niubi").start();
        new Thread(station,"huangniu").start();
    }

}

class BuyTicket implements Runnable{

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

    }

    //synchronized 同步方法,锁的是this
    private synchronized void buy() throws InterruptedException {//在此处添加synchronized,就解决了
        //判断是否有票
        if (ticketNums <= 0){
            flag = false;
            return;
        }
        //模拟延时
            Thread.sleep(100);
        //买票
        System.out.println(Thread.currentThread().getName() + "拿到了" + ticketNums--);
    }
}

实例二:解决银行取钱不安全

package com.lurenj.syn;

import com.lurenj.oop.demo05.A;

//不安全的取钱
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,"女友");

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

    //取钱
    //synchronized默认锁的是this,这里默认锁是<银行:模拟取款>,而我们实际需要锁的是<账户>
    @Override
    public void run() {

        synchronized (account){

            //判断是否有钱
            if (account.money - drawingMoney < 0){
                System.out.println(this.getName() + "钱不够,取不了");
                return;
            }

            //sleep可以放大问题的发生性
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            account.money = account.money - drawingMoney;
            nowMoney += drawingMoney;
            System.out.println(account.name + "余额为:" + account.money);
            //Thread.currentThread().getName() = this.getName(),因为该类继承了Thread类,getName是其中的方法
            System.out.println(this.getName() + "手里的钱" + nowMoney);
        }
    }
}

案例三:解决数组不安全问题

package com.lurenj.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(()->{
                synchronized (list){//通过锁住list对象来解决
                    list.add(Thread.currentThread().getName());
                }
            }).start();
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(list.size());
    }
}

案例四:解决数组不安全问题方法二,通过CopyOnWriteArrayList方法

package com.lurenj.syn;

import java.util.concurrent.CopyOnWriteArrayList;

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

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

        System.out.println(list.size());
    }
}
posted @   lurenj  阅读(56)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示