java同步工具Phaser

int32位 posted @ Sep 06, 2014 11:13:13 AM in java , 3837 阅读
转载请注明:http://krystism.is-programmer.com/若有错误,请多多指正,谢谢!

从java7开始在concurrent包中加入了Phaser类,它几乎可以取代CountDownLatch和CyclicBarrier, 其功能更灵活,更强大,支持动态调整需要控制的线程数。下面以一个具体实例说明这个Phaser类的用处,相信理解这个例子后,其功能不言而喻。

例子:有若干考生参加考试,考试科目是统一的,考试顺序为语文、数学、英语共三门,若其中一门挂科,则不能参加后面的考试。现在假设考试时间不受限制,开考时间以最后一名考完上一科时间为准,即先考完的考生并且成绩合格,需要参加下一门考试,则必须等待所有考生考完当科。

import java.util.*;
import java.util.concurrent.*;
class Examinee implements Runnable {
    public static Random random = new Random(new Date().getTime());
    private String name;
    private Phaser phaser;
    private int english;
    private int chinese;
    private int math;
    public Examinee(String name, Phaser phaser) {
        this.name = name;
        this.phaser = phaser;
    }
    public boolean english() {
        int time = random.nextInt(10);
        try {
            TimeUnit.SECONDS.sleep(time); /* 考试时间是一个随机数 */
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
        english = random.nextInt(101) ; /* 假定考试成绩是随机的 */
        if (english < 60) {
            System.out.printf("%s Failed to pass English!\n", name);
            phaser.arriveAndDeregister(); /* 考试不合格,取消考试资格 */
            return false;
        } else {
            phaser.arriveAndAwaitAdvance(); /* 通过考试,可以进行下一门考试 */
            return true;
        }
    }
    public boolean chinese() {
        int time = random.nextInt(10);
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
        chinese = random.nextInt(101) ;
        if (chinese < 60) {
            System.out.printf("%s Failed to pass Chinese!\n", name);
            phaser.arriveAndDeregister();
            return false;
        } else {
            phaser.arriveAndAwaitAdvance();
            return true;
        }
    }
    public boolean math() {
        int time = random.nextInt(10);
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
        math = random.nextInt(101) ;
        if (math < 60) {
            System.out.printf("%s Failed to pass Math!\n", name);
            phaser.arriveAndDeregister();
            return false;
        } else {
            phaser.arriveAndAwaitAdvance();
            return true;
        }
    }
    public void showInfo() {
        System.out.printf("%s\tChinese:%d\tEnglish:%d\tMath:%d\n", name, chinese, english, math);
        phaser.arriveAndDeregister();
    }
    @Override
    public void run() {
        phaser.arriveAndAwaitAdvance(); /* 等待考生做好准备,即在同一个起跑线上 */
        System.out.printf("%s is ready!\n", name);
        if (!chinese() || !english() || !math())
            return;
        showInfo(); /* 只显示所有科目均合格的考生分数 */
    }
}
public class PhaserDemo2 {
    public static void main(String[] args) {
        final String[] names = {"Jim", "Hary", "Mary", "Jhon", "Ali", "Lucy", "Wang", "Zhang", "Li", "Uhm", "Hey", "Gu", "Asu", "Who"};
        Phaser phaser = new Phaser(names.length);
        List<Thread> threads = new ArrayList<>(names.length);
        for (String name : names) {
            threads.add(new Thread(new Examinee(name, phaser), name)); /* 创建各个考生线程 */
        } 
        for (Thread t : threads) {
            t.start(); /* 开始考试 */
        }
        for (Thread t : threads) {
            try {
                t.join(); /* 等待考试结束 */
            } catch (InterruptedException e) {
                e.printStackTrace(System.err);
            }
        }
        System.out.printf("Terminal ? %s\n", phaser.isTerminated());
    }
}

由上面的例子,可以看出Phaser的功能。其中arrive方法很像CountDownLatch的countDown方法和CyclicBarrier的await方法,请自行比较之!Phaser类还有很多其他的功能,可以查看其API文档。

转载请注明:http://krystism.is-programmer.com/若有错误,请多多指正,谢谢!
  • 无匹配
  • 无匹配
tech 说:
2024年6月22日 17:51

It's late finding this act. At least, it's a thing to be familiar with that there are such events exist. I agree with your Blog and I will be back to inspect it more in the future so please keep up your act. Wikipedia Links

tech 说:
2024年6月24日 06:20

If your looking for Online Illinois license plate sticker renewals then you have need to come to the right place.We offer the fastest Illinois license plate sticker renewals in the state. embassy of new zealand in austrian

SEO 说:
2024年6月26日 15:19

Dominate search engine results pages with our expert SEO team. Click here for a free consultation! gmb management service

SEO 说:
2024年6月26日 18:51 This is my first time i visit here and I found so many interesting stuff in your blog especially it's discussion, thank you. buy pbn link
SEO 说:
2024年6月26日 18:51 This is my first time i visit here and I found so many interesting stuff in your blog especially it's discussion, thank you. buy pbn link
SEO 说:
2024年7月07日 20:11

What is an outstanding post! “I’ll be back” (to read more of your content). Thanks for the nudge! KingPlacing

SEO 说:
2024年7月16日 20:47

This is a great post. I like this topic.This site has lots of advantage.I found many interesting things from this site. It helps me in many ways.Thanks for posting this again. amarnath helicopter booking

SEO 说:
2024年7月25日 21:00

I am happy to find this post Very useful for me, as it contains lot of information. I Always prefer to read The Quality and glad I found this thing in you post. Thanks luxury-gadgets

mubashir 说:
2024年8月02日 19:57

Your blogs further more each else volume is so entertaining further serviceable It appoints me befall retreat encore. I will instantly grab your rss feed to stay informed of any updates. https://deutschbio.de/

SEO 说:
2024年8月31日 05:45

I found your this post while searching for information about blog-related research ... It's a good post .. keep posting and updating information. 壯陽藥品牌

SEO 说:
2024年10月15日 04:25

Mypuppen bietet lebensgroße Sexpuppen, die für ihre realistische Gestaltung und ihre langlebigen Materialien bekannt sind. Perfekt für Menschen, die auf Komfort und Detailtreue Wert legen. Lebensgroße Sexpuppen mypuppen

SEO 说:
2024年11月24日 04:13

This can be also a fairly beneficial writing that any of us absolutely beloved considering. Possibly not on a daily basis which often experience the likelihood to get a solution. 123movie

SEO 说:
2024年12月10日 05:37

Them believes altogether best suited. Every one of lesser areas ended up being built by lots of track record instruction. I like the necessary paperwork a good deal. 123movies.com

tech 说:
2024年12月12日 22:18

This is absolutely stunning work best spa jimbaran bali

tech 说:
2024年12月15日 04:57

Excellent website; I can handle the distinguished criticism. I'm going to continue and might even apply to my extremely fulfilling work as a pet sitter, but I still need to grow. Warm regards. admissibilité au visa canadien citoyens suisses


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter