提交 c5a2bd56 编写于 作者: 武汉红喜's avatar 武汉红喜

concurrent test

上级 e1f178b7
package org.hongxi.java.util.concurrent;
import java.util.concurrent.CountDownLatch;
/**
* Created on 2019/8/11.
*
* @author shenhongxi
*/
public class CountDownLatchTest {
public static void main(String[] args) {
int nThreads = 3;
CountDownLatch latch = new CountDownLatch(nThreads);
long begin = System.currentTimeMillis();
for (int i = 0; i < nThreads; i++) {
new Thread(new Task(i + 1, latch)).start();
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(System.currentTimeMillis() - begin);
}
static class Task implements Runnable {
private int id;
private CountDownLatch latch;
Task(int id, CountDownLatch latch) {
this.id = id;
this.latch = latch;
}
@Override
public void run() {
try {
Thread.sleep(1000 * id);
System.out.println(String.format("Sub Thread %d finished", id));
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
latch.countDown();
}
}
}
}
package org.hongxi.java.util.concurrent;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.*;
/**
* Created on 2019/8/11.
*
* @author shenhongxi
*/
public class InvokeAllTest {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
Collection<Callable<Long>> tasks = new ArrayList<>();
for (int i = 0; i < 3; i++) {
final int j = i + 1;
tasks.add(() -> {
Thread.sleep(1000 * j);
return System.currentTimeMillis();
});
}
try {
long begin = System.currentTimeMillis();
List<Future<Long>> futures = executorService.invokeAll(tasks);
futures.forEach(f -> {
try {
System.out.println(f.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
});
System.out.println(System.currentTimeMillis() - begin);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
executorService.shutdown();
}
}
}
package org.hongxi.java.util.concurrent;
import java.util.Arrays;
/**
* Created on 2019/8/11.
*
* @author shenhongxi
*/
public class JoinTest {
public static void main(String[] args) {
int nThreads = 3;
Thread[] threads = new Thread[nThreads];
for (int i = 0; i < nThreads; i++) {
final int j = i + 1;
threads[i] = new Thread(() -> {
try {
Thread.sleep(1000 * j);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
long begin = System.currentTimeMillis();
Arrays.stream(threads).forEach(t -> t.start());
Arrays.stream(threads).forEach(t -> {
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
System.out.println(System.currentTimeMillis() - begin);
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册