autoresetevent java_[原创]AutoResetEvent, ManualResetEvent的Java模拟

AutoResetEvent, ManualResetEvent是C#中常用的线程同步方法,在Java中可以模拟,AutoResetEvent使用Semaphore,增加的是许可证数量,程序里只有一个许可证,那么当这个许可被使用后,就会自动锁定。相反,ManualResetEvent使用countdownlatch,增加的是“latch”,也就是障碍,或者门闩;当障碍解除时,所有程序都可以运行而不被阻塞,如果要实现同步,就必须manual reset,也就是手动加latch。

import java.util.concurrent.Semaphore;

import java.util.concurrent.TimeUnit;

public class AutoResetEvent

{

private final Semaphore event;

private final Integer mutex;

public AutoResetEvent(boolean signalled)

{

event = new Semaphore(signalled ? 1 : 0);

mutex = new Integer(-1);

}

public void set()

{

synchronized (mutex)

{

if (event.availablePermits() == 0)

{

event.release();

}

}

}

public void reset()

{

event.drainPermits();

}

public void waitOne() throws InterruptedException

{

event.acquire();

}

public boolean waitOne(int timeout, TimeUnit unit) throws InterruptedException

{

return event.tryAcquire(timeout, unit);

}

public boolean isSignalled()

{

return event.availablePermits() > 0;

}

public boolean waitOne(int timeout) throws InterruptedException

{

return waitOne(timeout, TimeUnit.MILLISECONDS);

}

}

AutoResetEvent在MSDN中的例子程序在http://msdn.microsoft.com/en-us/library/system.threading.autoresetevent.aspx

我们可以改写一个java版本,用的是java版本的AutoResetEvent

import java.util.Date;

import java.util.Random;

class TermInfo

{

public long[] terms;

public int order;

public long baseValue;

public AutoResetEvent trigger;

}

public class AutoResetEventTest

{

private final static int numTerms = 3;

public static void main(String[] args0) throws InterruptedException

{

AutoResetEvent trigger = new AutoResetEvent(false);

TermInfo tinfo = new TermInfo();

Thread termThread;

long[] terms = new long[numTerms];

int result = 0;

tinfo.terms = terms;

tinfo.trigger = trigger;

for (int i = 0; i < numTerms; i++)

{

tinfo.order = i;

// Create and start the term calc thread.

TermThreadProc termThreadProc = new TermThreadProc(tinfo);

termThread = new Thread(termThreadProc);

termThread.start();

// simulate a number crunching delay

Thread.sleep(1000);

Date date = new Date();

tinfo.baseValue = Integer.parseInt(String.valueOf((date.getTime())).substring(10));

trigger.set();

termThread.join();

result += terms[i];

}

System.out.format("Result = %d", result);

System.out.println();

}

}

class TermThreadProc implements Runnable

{

public TermInfo termInfo;

public TermThreadProc(TermInfo termInfo)

{

this.termInfo = termInfo;

}

@Override

public void run()

{

TermInfo tinfo = termInfo;

System.out.format("Term[%d] is starting...", tinfo.order);

System.out.println();

// set the precalculation

Date date = new Date();

long preValue = Integer.parseInt(String.valueOf((date.getTime())).substring(10)) + tinfo.order;

// wait for base value to be ready

try

{

tinfo.trigger.waitOne();

}

catch (InterruptedException e)

{

e.printStackTrace();

}

Random rnd = new Random(tinfo.baseValue);

tinfo.terms[tinfo.order] = preValue * rnd.nextInt(10000);

System.out.format("Term[%d] has finished with a value of: %d", tinfo.order, tinfo.terms[tinfo.order]);

System.out.println();

}

}

//ManualResetEvent 的Java实现

import java.util.concurrent.CountDownLatch;

import java.util.concurrent.TimeUnit;

public class ManualResetEvent

{

private volatile CountDownLatch event;

private final Integer mutex;

public ManualResetEvent(boolean signalled)

{

mutex = new Integer(-1);

if (signalled)

{

event = new CountDownLatch(0);

}

else

{

event = new CountDownLatch(1);

}

}

public void set()

{

event.countDown();

}

public void reset()

{

synchronized (mutex)

{

if (event.getCount() == 0)

{

event = new CountDownLatch(1);

}

}

}

public void waitOne() throws InterruptedException

{

event.await();

}

public boolean waitOne(int timeout, TimeUnit unit) throws InterruptedException

{

return event.await(timeout, unit);

}

public boolean isSignalled()

{

return event.getCount() == 0;

}

public boolean waitOne(int timeout) throws InterruptedException

{

return waitOne(timeout, TimeUnit.MILLISECONDS);

}

}

MSDN地址:http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.aspx

Java测试:

import java.util.Scanner;

import java.io.IOException;

public class ManualResetEventTest

{

// mre is used to block and release threads manually. It is

// created in the unsignaled state.

static AutoResetEvent mre = new AutoResetEvent(false);

public static void main(String[] arg0) throws IOException, InterruptedException

{

System.out.println("\nStart 3 named threads that block on a ManualResetEvent:\n");

Scanner keyIn = new Scanner(System.in);

System.out.print("Press the enter key to continue");

keyIn.nextLine();

for (int i = 0; i <= 2; i++)

{

threadProc threadProc = new threadProc();

Thread t = new Thread(threadProc);

t.setName("Thread_" + i);

t.start();

}

Thread.sleep(500);

System.out.println("\nWhen all three threads have started, press Enter to call Set()"

+ "\nto release all the threads.\n");

keyIn.nextLine();

mre.set();

Thread.sleep(500);

System.out.println("\nWhen a ManualResetEvent is signaled, threads that call WaitOne()"

+ "\ndo not block. Press Enter to show this.\n");

keyIn.nextLine();

for (int i = 3; i <= 4; i++)

{

threadProc threadProc = new threadProc();

Thread t = new Thread(threadProc);

t.setName("Thread_" + i);

t.start();

}

Thread.sleep(500);

System.out.println("\nPress Enter to call Reset(), so that threads once again block"

+ "\nwhen they call WaitOne().\n");

keyIn.nextLine();

mre.reset();

// Start a thread that waits on the ManualResetEvent.

threadProc threadProc = new threadProc();

Thread t5 = new Thread(threadProc);

t5.setName("Thread_5");

t5.start();

Thread.sleep(500);

System.out.println("\nPress Enter to call Set() and conclude the demo.");

keyIn.nextLine();

mre.set();

}

}

class threadProc implements Runnable

{

@Override

public void run()

{

String name = Thread.currentThread().getName();

System.out.println(name + " starts and calls mre.WaitOne()");

try

{

ManualResetEventTest.mre.waitOne();

}

catch (InterruptedException e)

{

e.printStackTrace();

}

System.out.println(name + " ends.");

}

}

0

0

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2011-04-07 16:39

浏览 2539

评论

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/264581.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

用Jfree实现条形柱状图表,java代码实现

用Jfree实现条形柱状图表&#xff0c;java代码实现。可经经常使用于报表的制作&#xff0c;代码自己主动生成后能够自由查看。能够自由配置图表的各个属性&#xff0c;用来达到自己的要求和目的package test1;import org.jfree.chart.*; import org.jfree.chart.plot.*; import…

bzoj 2160: 拉拉队排练

Description 艾利斯顿商学院篮球队要参加一年一度的市篮球比赛了。拉拉队是篮球比赛的一个看点&#xff0c;好的拉拉队往往能帮助球队增加士气&#xff0c;赢得最终的比赛。所以作为拉拉队队长的楚雨荨同学知道&#xff0c;帮助篮球队训练好拉拉队有多么的重要。拉拉队的选拔工…

java long double精度丢失_long long类型转double类型部分精度丢失问题

我最近做了一道题&#xff0c;一个64位(unsigned __int64)范围内的数输出其除以1000的值&#xff0c;并按四舍五入保留小数点后三位。我刚开始直接写WA&#xff0c;结果发现当数比较大的时候&#xff0c;结果后几位精度总会丢失&#xff0c;只好手动模拟了一个&#xff0c;水过…

从服务器上自动更新系统补丁

对于经常重系统的用户或公司,每次安装系统后,必须得从微软网站上面下载补丁,这样很浪费时间. 如何从自己服务器上自动更新系统补丁,方法如下: 服务器端 服务器端需要安装一个更新服务器软件,如:SUS (下载地址http://www.onlinedown.net/soft/35844.htm) 客户端设置 开始 -- 运行…

搭建于 Cubieboard 之上的超小型实时监控平台 - mjpg篇

2019独角兽企业重金招聘Python工程师标准>>> 运行于 Cubieboard开发板 之上的个人笔记博客 http://cb.e-fly.org:81/archives/system-camera-monitor-mjpg-streamer.html 原文作者&#xff1a;Cannikin原文链接&#xff1a;http://forum.cubietech.com/forum ... p…

java 判断一个字符串是否由数字组成的_Java中怎样判断一个字符串是否是数字

展开全部1.使用Character.isDigit(char)判断String str "123abc";if (!"".equals(str)) {char num[] str.toCharArray();//把字符串转换为字符数组StringBuffer title new StringBuffer();//使用StringBuffer类&#xff0c;把非数e69da5e887aa323131333…

博客园的BLOG也申请了

BLOG申请了不少,但还没定居过------大都不怎么满意. 希望这回能让我安定下来... 20150413转载于:https://www.cnblogs.com/lxwy/archive/2008/05/28/4420771.html

Docker 入坑教程笔记

Docker 入坑教程笔记 视频网址B站&#xff1a;点这里 查询命令 man docker 简单启动和退出 docker run --name [容器名] -i -t ubuntu /bin/bash 交互启动虚拟机-t 提供伪tty终端docker ps [-a][-l]docker inspect [container name or id] 配置信息&#xff0c;有用数据docker …

安卓开发工具

Android 下载需要用到的工具:(1)下载JAVA的IDE开发工具– Eclipse到Eclipse官方网站下载Ecplise For Java EE的最新Windows版本 下载Ecplise(2)下载Java开发包 — Java SE Development Kit (JDK) JDK 6到Sun官方网站下载JDK6,选择JDK 6 Update 12 下载JDK6(3)下载Android开发包…

java http 返回码_【Java】Http返回状态码

来自HttpStatus&#xff0c;记录一下CONTINUE(100, "Continue"),SWITCHING_PROTOCOLS(101, "Switching Protocols"),PROCESSING(102, "Processing"),CHECKPOINT(103, "Checkpoint"),OK(200, "OK"),CREATED(201, "Creat…

启明星辰招聘

呵&#xff0c;好简单的工作。一狠心一咬牙不去了....... 不如现在的工作环镜好。岗位名称&#xff1a;安全工程师 人数&#xff1a;4工作地点&#xff1a;北京 薪水范围&#xff1a;4000-8000元/月投递简历邮箱&#xff1a;hrvenustech.com.cn公司网站&#xff1a;www.venuste…

515. 在每个树行中找最大值

您需要在二叉树的每一行中找到最大的值。 示例&#xff1a; 输入: 1/ \3 2/ \ \ 5 3 9 输出: [1, 3, 9]在真实的面试中遇到过这道题&#xff1f;class Solution {public List<Integer> largestValues(TreeNode root) {List<Integer> res new ArrayList&l…

加密的一些概念

明文&#xff1a;可以被人或程序识别的数据。例如一个文本文件、一段歌词、一个Word文档、一首MP3、一个图片文件、一段视频等等。 加密算法&#xff1a;将数据搞乱掉的方法。 密钥&#xff08;密码&#xff09;&#xff1a;一个你在进行加密操作时给出的字符串&#xff0c;让加…

java有装箱和拆箱吗_Java中装箱和拆箱,你真的都懂么?

在给部门做分享的时候&#xff0c;一位同学提问说一直没搞明白Java的装箱和拆箱&#xff0c;让我给讲解下&#xff0c;所以才有了下面这篇文章&#xff1a;本次文章根据PPT分享整理而成&#xff0c;会有5点&#xff1a;1、什么是装箱和拆箱&#xff1f;2、基本数据类型和包装类…

架构-浅谈MySQL数据库优化

主从复制博文&#xff1a;http://lizhenliang.blog.51cto.com/7876557/1290431 读写分离博文&#xff1a;http://lizhenliang.blog.51cto.com/7876557/1305083 MySQL-MMM博文&#xff1a;http://lizhenliang.blog.51cto.com/7876557/1354576 &#xff08;一&#xff09;数据库部…

项目发布相关

1.证书 cer文件需要上传电脑CSR文件&#xff0c;所以其他电脑如需使用需要创建者导出&#xff0c;用于在项目在真机运行或archive的时候签名&#xff0c;Code Signing Identity. 项目App ID&#xff0c;Provisioning Profile只要有管理员权限就可以申请&#xff0c;与cer文件对…

端午随笔

今天是端午节&#xff0c;我也毕业了正式开始了工作生涯&#xff0c;四年的大学生活画上了句号。面临我是什么&#xff0c;我该何去何从。人生的道路已经脱离自己在大学期间的人生规划。新的开始&#xff0c;就要有新的计划。我在一家公司已经实习了三个月了&#xff0c;我是我…

java base64解码出错_Java Base64解码错误及解决方法

问题提出&#xff1a;自己在做一个小网站充当练手&#xff0c;但是前端图片经过base64加密后传往后端在解码。但是一直都有问题&#xff0c;请大神赐教public static string base64toimg(string src) throws ioexception {string uuid uuid.randomuuid().tostring();stringbui…

PPT图片内嵌文字效果

【摘要】在报纸杂志上我们经常看到&#xff0c;有些图片中可以嵌入文字&#xff0c;如下图所示的效果&#xff1a;今天我们一起来学习一下这种效果是怎样生成的。 【正文】以下的操作步骤为PowerPoint 2013版本。 一 插入图片并编辑图片在【插入-联机图片】中搜索需要的图片。…

[天地君亲若追问 枉为知音百年羞]2008.06.07 晃荡在芳华

洞房悄悄静悠悠&#xff0c;花烛高烧暖心头&#xff0c; 喜气阵阵难抑止&#xff0c;这姻缘百折千磨方成啊就。 三月来&#xff0c;屡托刘兄把亲求&#xff0c;每遭见拒愿难酬&#xff0c; 从此我诗书五经无心看&#xff0c;三餐茶饭懒下喉&#xff0c; 日卧书斋愁脉脉&#xf…