多线程-交替打印FooBar(Exchanger+Semaphore)

本文介绍了一个使用Java实现的并发测试示例,通过Semaphore控制并发数,Exchanger进行线程间通信。主要展示了如何创建Bar和Foo线程类,它们分别交替执行并交换信息,展示了资源管理和线程同步的基本概念。
摘要由CSDN通过智能技术生成
package com.ctl;

import java.util.concurrent.Exchanger;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * <p>Title: Test</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2019</p>
 * <p>Company: www.hanshow.com</p>
 *
 * @author ctl
 * @version 1.0
 * @date 2021-09-27 19:37
 */
public class Test2 {
    static Semaphore semaphore = new Semaphore(1);

    static class Bar implements Runnable {
        private int times;
        private Exchanger<String> exchanger;

        public Bar(int times, Exchanger exchanger) {
            this.times = times;
            this.exchanger = exchanger;
        }

        @Override
        public void run() {
            for (int i = 0; i < times; i++) {
                try {
                    exchanger.exchange("");
                    try {
                        semaphore.acquire();
                    } catch (Exception e) {
                    }
                    System.out.println("bar");
                } catch (Exception e) {
                }
            }
        }
    }

    static class Foo implements Runnable {
        private int times;
        private Exchanger<String> exchanger;

        public Foo(int times, Exchanger exchanger) {
            this.times = times;
            this.exchanger = exchanger;
        }

        @Override
        public void run() {
            for (int i = 0; i < times; i++) {
                try {
                    exchanger.exchange("");
                    System.out.print("foo");
                    semaphore.release();
                } catch (Exception e) {
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        int times = 10;
        Exchanger<String> integerExchanger = new Exchanger<>();
        semaphore.acquire();
        new Thread(new Foo(times, integerExchanger)).start();
        new Thread(new Bar(times, integerExchanger)).start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
        }
        System.out.println("##");
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值