• 多线程优先级及同步


    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类的方法

  • 相关阅读:
    Oracle创建表空间、创建用户以及授权
    Oracle数据库安装图文操作步骤
    Oracle 11g数据库详细安装步骤图解
    Java 开发环境配置--eclipse工具进行java开发
    ExtJs常用布局--layout详解(含实例)
    HTTPS-HTTPS原理
    JavaScript: JavaScript的简介和入门代码演示
    HTML: 仿写一个财经类静态的网页
    CSS:仿写博客园写一个静态网页
    CSS:CSS定位和浮动
  • 原文地址:https://www.cnblogs.com/rrb520/p/5272417.html
Copyright © 2020-2023  润新知