java lock接口_Java Lock接口

Java Lock接口

java.util.concurrent.locks.Lock接口用作線程同步機制,類似于同步塊。新的鎖定機制更靈活,提供比同步塊更多的選項。 鎖和同步塊之間的主要區別如下:

序列的保證 - 同步塊不提供對等待線程進行訪問的序列的任何保證,但Lock接口處理它。

無超時,如果未授予鎖,則同步塊沒有超時選項。Lock接口提供了這樣的選項。

單一方法同步塊必須完全包含在單個方法中,而Lock接口的方法lock()和unlock()可以以不同的方式調用。

1 Lock接口的方法

以下是Lock類中可用的重要方法的列表。

方法

描述

public void lock()

獲得鎖

public void lockInterruptibly()

獲取鎖定,除非當前線程中斷

public Condition newCondition()

返回綁定到此Lock實例的新Condition實例

public boolean tryLock()

只有在調用時才可以獲得鎖

public boolean tryLock(long time, TimeUnit unit)

如果在給定的等待時間內自由,并且當前線程未被中斷,則獲取該鎖。

public void unlock()

釋放鎖

2?Lock接口的案例

以下TestThread程序演示了使用Lock接口的一些方法。 這里我們使用lock()獲取鎖和unlock()來釋放鎖。

package com.yiidian;

/**

* 一點教程網: http://www.yiidian.com

*/

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.\n", 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\n", 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();

}

}

輸出結果為:

Thread - 1 starts printing a document

Thread - 4 starts printing a document

Thread - 3 starts printing a document

Thread - 2 starts printing a document

Thread - 1 Time Taken 4 seconds.

Thread - 1 printed the document successfully.

Thread - 4 Time Taken 3 seconds.

Thread - 4 printed the document successfully.

Thread - 3 Time Taken 5 seconds.

Thread - 3 printed the document successfully.

Thread - 2 Time Taken 4 seconds.

Thread - 2 printed the document successfully.

在上面的示例中,使用ReentrantLock類作為Lock接口的一個實現。 ReentrantLock類允許線程鎖定方法,即使它已經具有其他方法鎖。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/395703.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/395703.shtml
英文地址,請注明出處:http://en.pswp.cn/news/395703.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

springcloud-05-ribbon中不使用eureka

ribbon在有eureka的情況下, 可以不使用eureka, 挺簡單, 直接上代碼 application.xml server:port: 7002 spring:# 設置eureka中注冊的名稱, 全小寫, 否則大小寫混雜出現問題application:name: microservice-consumer-movie-ribben-ymllogging:level:root: INFOorg.hibernate: I…

SQL mysql優化

慢查詢 如何通過慢查日志發現有問題的SQL? 查詢次數多且每次查詢占用時間長的SQL pt-query-digest分析前幾個查詢IO大的SQL pt-query-diges分析中的Rows examine項未命中索引的SQL pt-query-digest分析中Rows examine 和Rows Send的對比如何分析SQL查詢 使用explain…

轉: 關于 ssl的建立鏈接的過程

轉自: http://www.ruanyifeng.com/blog/2014/02/ssl_tls.html SSL/TLS協議運行機制的概述 作者: 阮一峰 日期: 2014年2月 5日 互聯網的通信安全,建立在SSL/TLS協議之上。 本文簡要介紹SSL/TLS協議的運行機制。文章的重點是設計思…

第一章第一個c#程序上機_我從第一個#100DaysOfCode中學到的東西

第一章第一個c#程序上機On May 17th, I completed my first round of #100DaysOfCode. In case you haven’t heard, #100DaysOfCode is a challenge, or movement, started by Alexander Kallaway for people interested in coding. The basis of the challenge is that you p…

[Swift通天遁地]一、超級工具-(2)制作美觀大方的環形進度條

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★?微信公眾號:山青詠芝(shanqingyongzhi)?博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)?GitHub地址&a…

SPOJ QTREE6 lct

題目鏈接 島娘出的題。還是比較easy的 #include <iostream> #include <fstream> #include <string> #include <time.h> #include <vector> #include <map> #include <queue> #include <algorithm> #include <stack> #in…

使用charles 抓取手機上的操作

Charles上的設置要截取iPhone上的網絡請求&#xff0c;我們首先需要將Charles的代理功能打開。在Charles的菜單欄上選擇“Proxy”->“Proxy Settings”&#xff0c;填入代理端口8888&#xff0c;并且勾上”Enable transparent HTTP proxying” 就完成了在Charles上的設置。如…

FreeCodeCamp納什維爾聚會的回顧

by Seth Alexander塞斯亞歷山大(Seth Alexander) FreeCodeCamp納什維爾聚會的回顧 (A Recap from the freeCodeCamp Nashville Meetup) At a recent freeCodeCamp meetup, a small group of campers got together to solve some coding challenges and we talk shop.在最近的f…

php查詢車位系統代碼,php車輛違章查詢數據示例

方便有車一族隨時了解自己是否有過交通違章&#xff0c;避免因遺忘或逾期處理違章罰單而造成的不必要損失。本代碼示例是基于聚合數據全國車輛違章查詢API的調用&#xff0c;有需要的可以往下看。使用前你需要&#xff1a;一、引入封裝好的請求類class.juhe.wz.phpheader(Conte…

[HNOI2011]XOR和路徑

嘟嘟嘟 一看到異或&#xff0c;就想到按位處理&#xff0e; 當處理到第\(i\)位的時候&#xff0c;\(f[u]\)表示節點\(u\)到\(n\)的路徑&#xff0c;這一位為\(1\)的期望&#xff0c;那么為\(0\)就是\(1 - f[u]\)&#xff0c;于是有\[f[u] \frac{1}{d[u]} (\sum _ {v \in V, w …

PHP 文件加密Zend Guard Loader 學習和使用(如何安裝ioncube擴展對PHP代碼加密)

一、大體流程圖 二、PHP 項目文件加密 下表列出了Zend產品中的PHP版本及其內部API版本和Zend產品版本。 如何加密請往后看 三、如何使用 第一步&#xff1a;確認當前環境 Amai Phalcon 前&#xff0c;請確認您具備以下兩個條件&#xff0c;如果您的環境不滿足此條件&#xff0c…

前向聲明

前向聲明的定義&#xff1a;有些時候我們可以聲明一些類但是并不去定義它&#xff0c;當然這個類的作用也很有限了。 如&#xff1a;class A; 聲明一個foo類&#xff0c;這個聲明&#xff0c;有時候也叫做前向聲明(forward declaration)&#xff0c;在聲明完這個foo類之后&…

php尋找文本,PHP文本數據庫的搜索方法_php

//php文本數據庫的搜索方法searchstr("/".preg_quote($searchstr)."/");//$searchstr是查找的關鍵字$recordsfile($file);//獲取所有的記錄數http://www.gaodaima.com/45906.htmlPHP文本數據庫的搜索方法_php//$file是查找的數據文件$search_reocrdspreg_g…

react vs 2017_我在React Europe 2017上學到了什么

react vs 2017by Nicolas Cuillery由Nicolas Cuillery 我在React Europe 2017上學到了什么 (What I learned at React Europe 2017) Few days ago, the 3rd edition of the biggest React conference in Europe took place in Paris. No heatwave or transportation strike th…

rem 之js代碼獲取font-size值(適合移動手機端)

這兩天學的是自適應&#xff0c;代碼有點亂。而且這幾天忙著寫實習報告&#xff0c;也沒有時間去整理。 但是&#xff0c;這下面代碼吧&#xff0c;是可以獲取html的font-size值的&#xff0c;然后用來設置相對單位rem的從而達到自適應效果的&#xff1b;看到紅色的width了吧&a…

關于C#中委托的一點理解

C#中委托是一種類型。可以這么籠統的理解&#xff1a;int型變量代表一個整型&#xff0c;而委托類型的變量代表一個方法的地址&#xff08;將方法名稱傳入constructor并實例化該委托變量&#xff09;。 --By Brisk Yu 1 為何要使用委托 我覺得網上關于什么現實生活的舉例并不好…

阿里的事前驗尸_(不太完全)100天的代碼-驗尸

阿里的事前驗尸by JS由JS (不太完全)100天的代碼-驗尸 ((Not quite) 100 Days of Code — A Postmortem) At the end of last year, I wrote about my experience coding and making daily commits to GitHub for 30 consecutive days. I also pledged to keep the streak goi…

php超市管理系統論文,超市管理系統的設計與實現

當今社會為信息社會&#xff0c;世界已經進入在計算機信息管理領域中激烈競爭的時代。對于一般的商戶而言&#xff0c;雜亂無章地陳放著的商品無疑會耗費他們大量的時間去對其整理并一一分類。他們需要更加便捷的手段去管理他們的商品以節約他們的時間成本以及人工成本。并且就…

只能輸入正整數 以及常用的正則表達式

<input typetext idSYS_PAGE_JumpPage nameSYS_PAGE_JumpPage size3 maxlength5 οnkeyupthis.valuethis.value.replace(/[^1-9]/D*$/,"") οndragenter"return false" οnpaste"return !clipboardData.getData(text).match(//D/)"" sty…

jq 自動滑動輪換(向后插入小塊)

// JavaScript Documentvar Marquee { arrIdObj : {/*marqueebox : {distance:-95,//移動距離delay:3000,//延遲時間speed:1000//移動時間},minCount:2 */}, //創建對象 startMarquee:function(){ //給參數賦值 if(this.arrIdObj ! null && typeof this.arrIdObj &qu…