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

  • 相关阅读:
    大数据挖掘算法篇之K-Means实例
    断篇-金融大数据最佳实践总结篇
    网络爬虫之Windows环境Heritrix3.0配置指南
    开源中文分词框架分词效果对比smartcn与IKanalyzer
    Eclipse整合Tomcat开发Dynamic Web Project环境总结
    c#系统消息类封装
    Uploadify v3.2.1 参数说明
    js 或 且 非
    数据注解特性--NotMapped
    SQLServer2008/2005 生成数据字典语句
  • 原文地址:https://www.cnblogs.com/timeboy/p/9464431.html
Copyright © 2011-2022 走看看