Skip to content

Commit

Permalink
concurrent test
Browse files Browse the repository at this point in the history
  • Loading branch information
javahongxi committed Aug 13, 2019
1 parent 91efa61 commit dc4da67
Show file tree
Hide file tree
Showing 3 changed files with 97 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package org.hongxi.java.util.concurrent;

import java.util.concurrent.CompletableFuture;

/**
* @author shenhongxi 2019/8/13
*/
public class CompletableFutureTest {

public static void main(String[] args) {
CompletableFuture.supplyAsync(() -> 1)
.thenApply(i -> i + 1)
.thenApply(i -> i * i)
.whenComplete((r, e) -> System.out.println(r));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package org.hongxi.java.util.concurrent;

import java.util.concurrent.locks.LockSupport;

/**
* @author shenhongxi 2019/8/13
*/
public class LockSupportTest {

public static void main(String[] args) {
Object blocker = new Object();
Thread t = new Thread(() -> {
System.out.println(System.currentTimeMillis());
LockSupport.park(blocker);
System.out.println(System.currentTimeMillis());
});
t.start();

try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
LockSupport.unpark(t);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package org.hongxi.java.util.concurrent;

import java.util.concurrent.Phaser;

/**
* @author shenhongxi 2019/8/13
* @see java.util.concurrent.CountDownLatch
* @see java.util.concurrent.CyclicBarrier
*/
public class PhaserTest {

public static void main(String[] args) {
int swimmers = 6;
Phaser phaser = new SwimmingPhaser();
phaser.register();
for (int i = 0; i < swimmers; i++) {
phaser.register();
new Thread(new Swimmer(phaser), "swimmer" + i).start();
}
phaser.arriveAndDeregister();

while (!phaser.isTerminated()) { }
System.out.println("比赛结束");
}

static class SwimmingPhaser extends Phaser {
private int phaseToTerminate = 2;

@Override
protected boolean onAdvance(int phase, int registeredParties) {
System.out.println("*第" + phase + "阶段完成*");
return phase == phaseToTerminate || registeredParties == 0;
}
}

static class Swimmer implements Runnable {
Phaser phaser;

Swimmer(Phaser phaser) {
this.phaser = phaser;
}

@Override
public void run() {
System.out.println("游泳选手" + Thread.currentThread().getName() + "已到达赛场");
phaser.arriveAndAwaitAdvance();

System.out.println("游泳选手" + Thread.currentThread().getName() + "已准备好");
phaser.arriveAndAwaitAdvance();

System.out.println("游泳选手"+Thread.currentThread().getName()+"完成比赛");
phaser.arriveAndAwaitAdvance();
}
}
}

0 comments on commit dc4da67

Please sign in to comment.