栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java多线程——线程的优先级及同步问题

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java多线程——线程的优先级及同步问题

文章目录
    • 线程优先级
    • 守护(daemon)线程
    • 线程同步
      • 并发
      • 队列和锁
      • 线程同步
    • 三个不安全案例
      • 不安全的买票
      • 不安全的取钱
      • 不安全的线程
    • 同步方法
      • 弊端
      • 同步块
      • 安全的买票
      • 安全的取钱
      • 安全的集合
      • 安全类型的集合——JUC

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

优先级的设定在start()调度前

优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了,这都是看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);
        Thread t5 = new Thread(myPriority);
        Thread t6 = new Thread(myPriority);

        //先设置优先级,再启动
        t1.start();
        
        t2.setPriority(1);
        t2.start();
        
        t3.setPriority(4);
        t3.start();
        
        t4.setPriority(Thread.MAX_PRIORITY);//MAX_PRIORITY=10
        t4.start();
        
        //报错二人组
        t5.setPriority(-1);
        t5.start();
        
        t6.setPriority(11);
        t6.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();
        You you = new You();

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

        thread.start();//上帝守护线程启动

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



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


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

线程同步 并发

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

  • 处理多线程问题时,多个线程访问同一个对象﹐并且某些线程还想修改这个对象.这时候我们就需要线程同步.线程同步其实就是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一个线程再使用
队列和锁

线程同步条件:队列+锁–>解决安全性

线程同步
  • 由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制synchronized ,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可.存在以下问题:
    • 一个线程持有会导致其他所有需要此锁的线程挂起;
    • 在多线程竞争下,加锁,释放锁会导致比较多的上下文切换 和 调度延时,引起性能问题;
    • 如果一个优先级高的线程等待一个优先级低的线程释放锁 会导致优先级低倒置,引起性能问题。
三个不安全案例 不安全的买票
//不安全的买票
//线程不安全,有负数,有重复
public class UnSafeBuyTicket {


    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();

        new Thread(station,"feliks").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 void buy() throws InterruptedException {
        //判断是否有票
        if (ticketNums<=0){
            flag = false;
            return;
        }
        //模拟延时
        Thread.sleep(100);
        //买票
        System.out.println(Thread.currentThread().getName()+"拿到第"+ticketNums--+"张");
    }
}
不安全的取钱
//不安全的取钱
//两个人去银行取钱,账户
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;//账户
    //取了多少钱
    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(Thread.currentThread().getName()+"钱不够,无法取出");
            return;
        }

        //sleep可以放大问题的发生行
        try {
            Thread.sleep(1000);
        } 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) {
        List list = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            new Thread(()->{
                list.add(Thread.currentThread().getName());
            }).start();
        }
        //放大问题后仍不安全:不到10000
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(list.size());
    }
}
同步方法
  • 由于我们可以通过private关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制﹐这套机制就是synchronized关键字,它包括两种用法︰synchronized方法和synchronized块.
同步方法:public synchronized void method(int args){}
  • synchronized方法控制对“对象”的访问﹐每个对象对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行﹐否则线程会阻塞,方法一旦执行﹐就独占该锁,直到该方法返回才释放锁﹐后面被阻塞的线程才能获得这个锁,继续执行
缺陷:若将一个大的方法声明为 synchronized 将会影响效率
弊端

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

给buy方法加上synchronized

public class SafeBuyTicket {

    public static void main(String[] args) {
        BuyTicket1 station1 = new BuyTicket1();

        new Thread(station1,"feliks").start();
        new Thread(station1,"你").start();
        new Thread(station1,"可恶的黄牛").start();
    }
}


class BuyTicket1 implements Runnable{

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

//synchronized 同步方法,锁的是this=============
    private synchronized void buy() throws InterruptedException {
        //判断是否有票
        if (ticketNums<=0){
            flag = false;
            return;
        }
        //模拟延时
        Thread.sleep(100);
        //买票
        System.out.println(Thread.currentThread().getName()+"拿到第"+ticketNums--+"张");
    }
}
安全的取钱

用同步代码块

package net.cqwu.syn;


//不安全的取钱
//两个人去银行取钱,账户
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,"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;//账户
    //取了多少钱
    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(Thread.currentThread().getName()+"钱不够,无法取出");
                return;
            }

            //sleep可以放大问题的发生行
            try {
                Thread.sleep(1000);
            } 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);
        }
    }
}
安全的集合
//线程安全的集合
public class UnsafeList {
    public static void main(String[] args) {
        List list = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            new Thread(()->{
                //锁住list
                synchronized (list){
                    list.add(Thread.currentThread().getName());
                }

            }).start();
        }
        //放大问题后仍不安全:不到10000
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(list.size());
    }
}
安全类型的集合——JUC
import java.util.concurrent.CopyOnWriteArrayList;

//测试JUC安全类型的集合
public class TestJUC {
    public static void main(String[] args) {
        CopyOnWriteArrayList list = new CopyOnWriteArrayList();
        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());
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/397155.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号