批次号java算法_java重复批次执行

方案1  使用Phaser

方案2  使用CyclicBarrier

package mon.config;

import static mon.config.OneTwoOneTwoTest4.MAX;

import static mon.config.OneTwoOneTwoTest4.NUM;

import static mon.config.OneTwoOneTwoTest4.phaser;

import java.util.concurrent.Phaser;

public class OneTwoOneTwoTest4 {

static int NUM = 0;

static int MAX = 6;

static Object LOCK = new Object();

static Phaser phaser = new Phaser(2);

public static void main(String[] args) throws InterruptedException {

Thread thread1 = new ThreadTest4();

thread1.start();

Thread thread2 = new ThreadTest4();

thread2.start();

thread1.join();

thread2.join();

}

}

class ThreadTest4 extends Thread {

public void run() {

while (true) {

synchronized (phaser) {

NUM = NUM + 1;

System.err.println(NUM + " ====" + Thread.currentThread());

if (NUM >= MAX) {

break;

}

}

phaser.arriveAndAwaitAdvance();

}

};

}

package mon.config;

import static mon.config.OneTwoOneTwoTest5.MAX;

import static mon.config.OneTwoOneTwoTest5.NUM;

import static mon.config.OneTwoOneTwoTest5.cyclicBarrier;

import java.util.concurrent.CyclicBarrier;

public class OneTwoOneTwoTest5 {

static int NUM = 0;

static int MAX = 6;

static CyclicBarrier cyclicBarrier;

public static void main(String[] args) throws InterruptedException {

cyclicBarrier = new CyclicBarrier(2);

Thread thread1 = new ThreadTest5();

thread1.start();

Thread thread2 = new ThreadTest5();

thread2.start();

thread1.join();

thread2.join();

}

}

class ThreadTest5 extends Thread {

public void run() {

while (true) {

synchronized (ThreadTest5.class) {

NUM = NUM + 1;

System.err.println(NUM + " ====" + Thread.currentThread());

if (NUM >= MAX) {

break;

}

}

try {

cyclicBarrier.await();

} catch (Exception e) {

e.printStackTrace();

}

}

};

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值