zoukankan      html  css  js  c++  java
  • java并发Lock接口

    使用lock()获取锁,unlock()释放锁。

    import java.util.concurrent.locks.Lock;
    import java.util.concurrent.locks.ReentrantLock;
    class PrintDemo {
     
       private final Lock queueLock = new ReentrantLock();
     
       public void print() {
          queueLock.lock();
          try {
             Long duration = (long) (Math.random() * 10000);
             System.out.println(Thread.currentThread().getName() 
                "  Time Taken " + (duration / 1000) + " seconds.");
             Thread.sleep(duration);
          catch (InterruptedException e) {
             e.printStackTrace();
          finally {
             System.out.printf("%s printed the document successfully. ", Thread.currentThread().getName());
             queueLock.unlock();
          }
       }}class ThreadDemo extends Thread {
       PrintDemo  printDemo;
     
       ThreadDemo( String name,  PrintDemo printDemo) {
          super(name);
          this.printDemo = printDemo;
       }   
     
       @Override
       public void run() {
          System.out.printf("%s starts printing a document ", Thread.currentThread().getName());
          printDemo.print();
       }}public class TestThread {
     
       public static void main(String args[]) {
          PrintDemo PD = new PrintDemo();
     
          ThreadDemo t1 = new ThreadDemo( "Thread - 1 ", PD );
          ThreadDemo t2 = new ThreadDemo( "Thread - 2 ", PD );
          ThreadDemo t3 = new ThreadDemo( "Thread - 3 ", PD );
          ThreadDemo t4 = new ThreadDemo( "Thread - 4 ", PD );
     
          t1.start();
          t2.start();
          t3.start();
          t4.start();
       }
    }

  • 相关阅读:
    Python 函数 I
    jmeter-将上一个接口的返回值作为下一个接口的参数
    Python 文件的操作
    Python 基础数据类型 VI
    Pyhton 基础数据类型 V (补充)
    Python 基础数据类型 IV (集合)
    Python 基础数据类型 III (字典)
    难道是你?
    是你啦
    checkWeb
  • 原文地址:https://www.cnblogs.com/timeboy/p/9464431.html
Copyright © 2011-2022 走看看