update at 2019-07-19 14:14:12 by ehlxr

dev
ehlxr 2019-07-19 14:14:12 +08:00
parent 5c80704a14
commit 52178b4ff1
3 changed files with 97 additions and 64 deletions

View File

@ -1,64 +0,0 @@
package me.ehlxr;
import com.google.common.collect.Lists;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
*
*
* @author lixiangrong
* @since 2019-07-18.
*/
public class BarrierTest {
public static void main(String[] args) {
Barrier barrier = new Barrier(10, 3);
final Thread[] threads = new Thread[20];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(() -> {
if (barrier.allow()) {
System.out.println("yes");
}
});
threads[i].start();
}
for (Thread t : threads) {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Barrier {
private AtomicInteger op = new AtomicInteger(0);
private List<Integer> sources = Lists.newArrayList();
private int base;
private int rate;
public boolean allow() {
return sources.get(op.incrementAndGet() % base) < rate;
}
private Barrier() {
}
public Barrier(int base, int rate) {
this.base = base;
this.rate = rate;
for (int i = 0; i < 10; i++) {
sources.add(i);
}
Collections.shuffle(sources);
}
}

View File

@ -0,0 +1,57 @@
package me.ehlxr.rate;
/**
* @author lixiangrong
* @since 2019-07-18.
*/
public class Main {
public static void main(String[] args) {
RateBarrier rateBarrier = new RateBarrier(10, 3);
final Thread[] threads = new Thread[20];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(() -> {
if (rateBarrier.allow()) {
System.out.println("this is on 3");
} else {
System.out.println("this is on 7");
}
});
threads[i].start();
}
for (Thread t : threads) {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// Output:
/*
this is on 7
this is on 7
this is on 7
this is on 7
this is on 3
this is on 7
this is on 3
this is on 7
this is on 7
this is on 3
this is on 7
this is on 7
this is on 7
this is on 7
this is on 3
this is on 7
this is on 3
this is on 7
this is on 7
this is on 3
*/

View File

@ -0,0 +1,40 @@
package me.ehlxr.rate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
*
*
* @author lixiangrong
* @since 2019-07-19.
*/
public class RateBarrier {
private AtomicInteger op = new AtomicInteger(0);
private List<Integer> source;
private int base;
private int rate;
public boolean allow() {
return source.get(op.incrementAndGet() % base) < rate;
}
private RateBarrier() {
}
public RateBarrier(int base, int rate) {
this.base = base;
this.rate = rate;
source = new ArrayList<>(base);
for (int i = 0; i < base; i++) {
source.add(i);
}
// 打乱集合顺序
Collections.shuffle(source);
}
}