zoukankan      html  css  js  c++  java
  • java多线程lock的使用

    看代码:

    package com.ming.thread.reentrantlock;
    
    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    
    public class MyService {
    
        private Lock lock=new ReentrantLock();
        
        public void testMethodA(){
            lock.lock();
            for(int i=0;i<5;i++){
                System.out.println("方法A"+"ThreadName="+Thread.currentThread().getName()+"("+(i+1)+")");
            }
            lock.unlock();
        }
        
        public void testMethodB(){
            lock.lock();
            for(int i=0;i<5;i++){
                System.out.println("方法B"+"ThreadName="+Thread.currentThread().getName()+"("+(i+1)+")");
            }
            lock.unlock();
        }
        
        
    }
    package com.ming.thread.reentrantlock;
    
    public class ThreadA extends Thread{
    
        private MyService service;
        
        public ThreadA(MyService service){
            super("A");
            this.service=service;
        }
        
        public void run(){
            service.testMethodA();
        }
    }
    package com.ming.thread.reentrantlock;
    
    public class ThreadB extends Thread{
    
        private MyService service;
        
        public ThreadB(MyService service){
            super("B");
            this.service=service;
        }
        
        public void run(){
            service.testMethodB();
        }
    }
    package com.ming.thread.reentrantlock;
    
    public class Run {
    
        public static void main(String[] args) {
            MyService service=new MyService();
            ThreadA a=new ThreadA(service);
            ThreadB b=new ThreadB(service);
            a.start();
            b.start();
        }
    }

    更多运用:http://blog.csdn.net/vking_wang/article/details/9952063

  • 相关阅读:
    C++分数类
    2019 SDN大作业
    个人作业-软工实践总结
    2019 SDN上机第7次作业
    2019 SDN上机第6次作业
    2019 SDN课程阅读作业(2)
    个人作业--软件评测
    2019 SDN上机第5次作业
    2019 SDN上机第4次作业
    2019 SDN第一次阅读作业
  • 原文地址:https://www.cnblogs.com/huzi007/p/7121866.html
Copyright © 2011-2022 走看看