zoukankan      html  css  js  c++  java
  • 多线程-lock锁

    package 多线程.lock锁;
    
    import java.util.concurrent.locks.ReentrantLock;
    
    /*、
    *
    * //同步代码块
    *
    * */
    public class Sale implements Runnable {
        private int m = 10;
        private  ReentrantLock  relock =  new ReentrantLock();
        boolean f =true;
        @Override
        public void run() {
            //保证每一个线程都必须完成,其他线程才能抢  使用同步锁 出现共享变量都要加锁  多个线程必须持有同一个锁
            while (f) {
                relock.lock();
                    if(m > 0) {
                        System.out.println(Thread.currentThread().getName() + "卖票---" + (m--) + "");
                    }else {
                        f =false;
                    }
                relock.unlock();
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    package 多线程.lock锁;
    
    import 多线程.synchronized锁.Sale2;
    
    public class Demo02 {
        public static void main(String[] args) throws InterruptedException {
            Sale sale = new Sale();
    
            Thread t1 =new Thread(sale,"窗口1");
            Thread t2 =new Thread(sale,"窗口2");
            Thread t3 =new Thread(sale,"窗口3");
    
    
            t1.setDaemon(true);//将该线程标记为守护线程或用户线程。
            t1.start();
            t1.yield();
            t1.join(10);//等待该线程终止
            System.out.println(t2.getPriority());//默认优先级为5
            t2.setPriority(7);//更改线程的优先级。
            t2.start();
            t3.start();
        }
    }
  • 相关阅读:
    Java 之 Maven 基础
    JavaScript 之 RegExp 对象
    Java 之 Jedis
    Java 之 Redis 基础
    Java 之 NOSQL
    JavaWeb 之 JSON
    JavaWeb 之 Ajax
    【LeetCode-数组】外观数列
    【LeetCode-树】从先序遍历还原二叉树
    【LeetCode-数组】搜索二维矩阵 II
  • 原文地址:https://www.cnblogs.com/houtian2333/p/10702560.html
Copyright © 2011-2022 走看看