lock 線程 java_JAVA多線程-基礎Lock Condition 并發集合

跟上一篇文章比較,這次改進了之前的代碼,使用了Lock Condition 和并發集合.代碼量減了一些,并且更加容易讀了.

這篇代碼是上一篇的改進版,邏輯在前篇有說明,以防大家看不到,我再重現貼一遍.后續會使用高階的線程工具再次改進,以求代碼更簡單.代碼的邏輯:

1)SProducer不停的產生number到queue中.

2)3個carrier不停的取出queue中的number.

3)如果queue中存在10個剩余number時,SProducer會停下來等Carrier消費一些后再生產.

4)如果Carrier發現queue中沒有number時,會等待.

5)如果Carrier取出的數字末尾為4, 則會挑起罷工事件.

6)Carrier罷工會引發一個Negotiation線程進行談判.

7)罷工階段SProducer和所有Carrier均停工.

8)Negotiation如果發現取出的number首位為3或者7,將引發談判失敗.

9)如果談判成功,則恢復工作,如果談判失敗,則破產,所有線程均退出.

注意:使用lock的時候一定要注意, lock()和unlock()方法一定要成對出現. 最好放到try{}finally{}中,這樣,unlock()方法必會調到.倘若沒有使用unlock()就return了,會導致線程死鎖.

package concurrency;

import java.util.ArrayList;

import java.util.concurrent.ArrayBlockingQueue;

import java.util.concurrent.locks.Condition;

import java.util.concurrent.locks.ReentrantLock;

public class Producer extends Thread {

private final static ArrayBlockingQueue numbers = new ArrayBlockingQueue(10);

private final static ArrayList threads = new ArrayList();

private volatile boolean negotiating = false;

private ReentrantLock negotiationLock = new ReentrantLock();

private Condition negotiationCondition = negotiationLock.newCondition();

private class Negotiation implements Runnable {

private String number;

private Negotiation(String number) {

this.number = number;

}

public void run() {

try {

System.out.println("Start negotiation...");

sleep(5000);

if (number.startsWith("7") || number.startsWith("3")) {

System.out.println("Negotiation broken.");

for (Thread t : threads) {

t.interrupt();

}

System.out.println("Negotiation broken post handle.");

return;

}

System.out.println("Negotiation succeeds.");

} catch (InterruptedException e) {

System.out.println("Middle man is killed.");

}

negotiationLock.lock();

negotiating = false;

negotiationCondition.signalAll();

negotiationLock.unlock();

}

}

private class Carrier implements Runnable {

private String name;

private Carrier(String name) {

this.name = name;

}

public void run() {

while(true) {

try{

negotiationLock.lock();

while(negotiating) {

try {

System.out.println("Carrier ["+name+"] join stricks.");

negotiationCondition.await();

} catch (InterruptedException e) {

System.out.println("Negotiation fails. Carrier [" + name + "] retires.");

return;

}

}

} finally {

negotiationLock.unlock();

}

String number;

try {

number = numbers.take();

System.out.println("Carrier [" + name + "] carries "+ number +" out of List;");

} catch (InterruptedException e1) {

System.out.println("Negotiation fails. Carrier [" + name + "] retires.");

return;

}

if (number.endsWith("4")) {

try {

negotiationLock.lock();

while (negotiating) {

try {

negotiationCondition.await();

} catch (InterruptedException e) {

System.out.println("Negotiation fails. Carrier [" + name + "] retires.");

return;

}

}

negotiating = true;

System.out.println("Stricks happen on number:"+number);

new Thread(new Negotiation(number)).start();

} finally {

negotiationLock.unlock();

}

}

}

}

}

public void run() {

Thread a = new Thread(new Carrier("a"));

Thread b = new Thread(new Carrier("b"));

Thread c = new Thread(new Carrier("c"));

threads.add(this);

threads.add(a);

threads.add(b);

threads.add(c);

a.start();

b.start();

c.start();

this.produceNumbers();

}

private void produceNumbers() {

while (true) {

while(negotiating) {

negotiationLock.lock();

try {

System.out.println("Stricking... Producer waiting for negotiation result.");

negotiationCondition.await();

System.out.println("Negotiation succeeds. Producer happy.");

} catch (InterruptedException e) {

System.out.println("Negotiation fails. Producer breaks up.");

return;

} finally {

negotiationLock.unlock();

}

}

String number = ""+new java.util.Random().nextInt(47);

try {

numbers.put(number);

System.out.println("Produce number " + number + " into List;");

} catch (InterruptedException e) {

System.out.println("Negotiation fails. Producer breaks up.");

return;

}

}

}

public static void main(String[] args) {

new Producer().start();

}

}

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

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

相關文章

mycat mysql ha 方案_7、基于 HA 機制的 Mycat 高可用--mycat

在實際項目中,Mycat 服務也需要考慮高可用性,如果 Mycat 所在服務器出現宕機,或 Mycat 服務故障,需要有備機提供服務,需要考慮 Mycat 集群。1、 高可用方案使用 HAProxy Keepalived 配合兩臺 Mycat 搭起 Mycat 集群&a…

爬蟲scrapy模塊

首先下載scrapy模塊 這里有驚喜 https://www.cnblogs.com/bobo-zhang/p/10068997.html 創建一個scrapy文件 首先在終端找到一個文件夾 輸入 scrapy startproject jy (項目件名) 修改setting文件配置 # Crawl responsibly by identifying yourself (and your website) on the us…

python canvas畫移動物體_如何實現Canvas圖像的拖拽、點擊等操作

上一篇Canvas的博文寫完后,有位朋友希望能對Canvas繪制出來的圖像進行點擊、拖拽等操作,因為Canvas繪制出的圖像能很好的美化。好像是想做爐石什么的游戲,我也沒玩過。Canvas在我的理解中就好像在一張畫布上繪制圖像,它只能看到卻…

Git基礎知識教程整理(Git基本操作)

Git簡介 Git是目前世界上最先進的分布式版本控制系統(沒有之一)。Linux之父Linux用C語言寫了Git分布式版本控制系統。 分布式版本控制系統與集中式版本控制系統的區別 區別分布式集中式中央服務器有,版本庫集中存放在中央服務器,工…

python plot map_使用matplotlibbasemap在邊界打印

我在繪制多邊形時遇到了困難,例如,在使用matplotlib basemap生成的地圖邊界上繪制多邊形。在下面的示例中,地圖邊界由日期線指定。我試圖通過指定三角形頂點的坐標來繪制一個跨越日期線的三角形。當所有的坐標都在地圖內時,這種方…

SQL查詢語句 group by后, 字符串合并

合并列值 --******************************************************************************************* 表結構,數據如下: id value ----- ------ aa bb aaa bbb ccc 需要得到結果: id values ------ ----------- aa,bb aaa…

Git 基礎 —— 常用命令

Git 基礎學習系列 Git 基礎 —— 安裝 配置 別名 對象Git 基礎 —— 常用命令Git 基礎 —— 常見使用場景Git基礎 —— Github 的使用git init 創建 Git 本地倉庫 遠端無倉庫,本地無倉庫,本地新建一個倉庫 git init git_learning 遠端有倉庫,…

python安裝caffe_Linux下caffe的安裝

下載caffe并保存到一個目錄下(推薦放到 /home 目錄)安裝依賴項:sudo apt-get install libprotobuf-dev libleveldb-dev libsnappy-dev libopencv-dev libhdf5-serial-dev protobuf-compilersudo apt-get install --no-install-recommends libboost-all-devsudo apt-…

linux 訪問Windows 共享文件的方法

2019獨角獸企業重金招聘Python工程師標準>>> 1 安裝Samba服務 2 啟動 samba服務 /etc/init.d/smb restart 3 安裝插件 cifs解決只讀掛載:yum install cifs-utils.x86_64 4 在windows下共享一個可以用的文件夾 5 將 windows 共享文件夾掛載到linux上 命令…

基于Blink構建親聽項目以及全鏈路debug項目實時響應能力

案例與解決方案匯總頁:阿里云實時計算產品案例&解決方案匯總 本文全面總結了大數據項目組在親聽項目以及全鏈路debug項目上進行的實時流處理需求梳理,架構選型,以及達成效果 一、背景介紹 1.1親聽項目 親聽項目專注于幫助用戶收集、展示、…

python的重點_python知識點

"""author:lei"""import os#os.path.join() 將分離的部分合成一個整體filenameos.path.join(/home/ubuntu/python_coding,split_func)print filename#輸出為:/home/ubuntu/python_coding/split_func#os.path.splitext()將文件名和擴展…

在既有系統中打通Apache Ignite、MySQL和Node.js

為什么80%的碼農都做不了架構師?>>> 介紹 在本系列的第一篇文章中,安裝了Node.js、Ignite的Node.js瘦客戶端包,并且測試了一個示例應用。在本文中,可以看一下Ignite在處理其它數據源(比如關系數據庫&#…

java hashmap 的api_JAVA基礎--JAVA API集合框架(ArrayList、HashSet、HashMap使用)

一、集合Collection1. 集合介紹變量:表示的內存中的一個空間,只能保存確定類型的單個數據數組:表示的是內存中的多個連續的空間,這些空間中可以存儲多個同類型的數據。后期繼續學習面向對象技術,我們在程序中開始創建對…

Vue進階知識筆記

利用v-for循環出的多個li標簽&#xff0c;點擊不同的li變換顏色 方法一 <ul v-for"(item,index) in list" :key"index" class"details"><li ref"lisd" click"faillist(index)" :class"{active:ind index}&qu…

teamcity mysql 配置_CentOS 7 上 TeamCity 安裝

CentOS 7 上 TeamCity 安裝非入門教程, 初次接觸centos/docker的朋友需要謹慎一. 安裝 MySQL為了后續的需要, 這里安裝了 Docker, 當然如果你已經有了 MySQL 或者其它推薦的數據庫[MySQL, PostgreSQL, Oracle, MS SQL], 則可忽略1. 安裝 Docker補充:# 啟動dockersudo systemctl…

Python網絡請求庫Requests,媽媽再也不會擔心我的網絡請求了(二)

本文同步發表于我的微信公眾號&#xff0c;掃一掃文章底部的二維碼或在微信搜索 極客導航 即可關注&#xff0c;每個工作日都有文章更新。 一、概況 接著上篇說&#xff0c;如果你真以為Requests網絡請求庫只有Get請求和Post請求&#xff0c;那就大錯特錯了。它還一些其他用法&…

dbunit java_java - 錯誤地拋出了Java DBUnit AmbiguousTableNameException - 堆棧內存溢出

我正在嘗試DBUnit(2.6.0)&#xff0c;我正在嘗試導出我的完整數據庫(PostgreSQL)。 但是拋出以下異常&#xff1a;線程“main”中的異常org.dbunit.database.AmbiguousTableNameException&#xff1a;FLYWAY_SCHEMA_HISTORY這是正確的行為&#xff0c;因為我有兩個具有相同名稱…

Docker 命令詳解(run篇)

參考&#xff1a;https://www.cnblogs.com/yfalcon/p/9044246.html 命令格式&#xff1a;docker run [OPTIONS] IMAGE [COMMAND] [ARG...]Usage: Run a command in a new container中文意思為&#xff1a;通過run命令創建一個新的容器&#xff08;container&#xff09; 常用選…

java 同步 lock_關于java:同步是否像Lock.lock()一樣駐留并發線程?

當我們調用lock.lock()或嘗試輸入synchronized塊時&#xff0c;如果其他某個線程已經獲得了該鎖&#xff0c;則我們的線程將阻塞。 現在我的問題是&#xff0c;當我們查看lock.lock()的實現時&#xff0c;它會將獲取鎖委托給AQS&#xff0c;而AQS實際將當前線程駐留在該線程中(…

Idea項目中常見錯誤及筆記(Old)

1、Idea基礎設置&#xff1a; File-->settings--> 1>修改字體&#xff1a;Font 2>修改編碼格式&#xff1a;File Encodings(全部UTF-8,右下方復選框勾中--防止程序中的漢字轉為ASCII碼) 3>修改行號&#xff1a;Appearance&#xff1a;show line numbers show me…