• 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();
       }
    }

  • 相关阅读:
    forin语句和document.write换行
    输入日期计算出当天是星期几
    输入半径求圆的面积和简单的ASCII码转化
    一段简单的代码用来在网页上测试javascript程序
    如何在ubuntu下修改hosts?
    如何在终端上打出货币符号和算式
    C#文件监控
    JavaScript类的写法 ( 仿jQuery )
    JavaScript类创建的几种方式
    (转)程序员的十层楼:大家都来测测你的技术层级
  • 原文地址:https://www.cnblogs.com/timeboy/p/9464431.html
Copyright © 2020-2023  润新知