java重复批次执行

方案1  使用Phaser
方案2  使用CyclicBarrier


package com.eyu.ahxy.module.common.config;

import static com.eyu.ahxy.module.common.config.OneTwoOneTwoTest4.MAX;
import static com.eyu.ahxy.module.common.config.OneTwoOneTwoTest4.NUM;
import static com.eyu.ahxy.module.common.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 com.eyu.ahxy.module.common.config;

import static com.eyu.ahxy.module.common.config.OneTwoOneTwoTest5.MAX;
import static com.eyu.ahxy.module.common.config.OneTwoOneTwoTest5.NUM;
import static com.eyu.ahxy.module.common.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();
			}

		}
	};

}

你可能感兴趣的:(java)