zoukankan      html  css  js  c++  java
  • 多线程优先级及同步

    6、线程的优先级
      Thread.MIN_PRIORITY = 1
      Thread.NORM_PRIORITY = 5
      Thread.MAX_PRIORITY = 10
    7、线程同步
      ①使用同步代码块
        

    public class ThreadDemo {

      public static void main(String[] args) {

        MyThread thread1=new MyThread();

        new Thread(thread1).start();

        new Thread(thread1).start();

        new Thread(thread1).start();

        new Thread(thread1).start();

      }

    }

    class MyThread implements Runnable{

      private int ticket=5;

      public MyThread(){

      }

    public void run(){

        for(int i=0;i<100;i++){

          synchronized (this) {

            if(ticket>0){

            try {

            Thread.sleep(1000);

            } catch (InterruptedException e) {

            e.printStackTrace();

            }

        System.out.println("卖出了第"+ticket--+"张票");

            }

        }

      }

      }

    }

      ②使用同步方法

    public class ThreadDemo {

        public static void main(String[] args) {

          MyThread thread1=new MyThread();

          new Thread(thread1).start();

          new Thread(thread1).start();

          new Thread(thread1).start();

          new Thread(thread1).start();

        }

    }

    class MyThread implements Runnable{

        private int ticket=5;

        public void run(){

          for(int i=0;i<100;i++){

          this.sale();

        }

    }

    public synchronized void sale(){

        if(ticket>0){

        try {

        Thread.sleep(1000);

        } catch (InterruptedException e) {

        e.printStackTrace();

        }

        System.out.println("卖出了第"+ticket--+"张票");

        }

      }

    }

    8、wait 和 sleep 比较

      ①wait别的线程可以访问锁定对象,它是Object类的方法,注意:调用wait方法的时候必须锁定该对象

      ②sleep时别的线程不可以访问锁定对象,它是Thread类的方法

  • 相关阅读:
    洛谷 P2677 超级书架 2 题解
    洛谷 P3957 跳房子 二分+DP检验+单调队列优化
    BZOJ 1030 AC自动机+DP
    SPOJ-EPALIN 字符串哈希 回文
    URAL-1989 树状数组+字符串哈希
    POJ-2774 字符串哈希+二分
    CCF 201709-5 除法(线段树)
    CCF CSP个人题解汇总
    CCF CSP历年一二题代码汇总
    CCF 201803-4 棋局评估 (对抗搜索)
  • 原文地址:https://www.cnblogs.com/rrb520/p/5272417.html
Copyright © 2011-2022 走看看