Skip to content

Commit

Permalink
线程池优雅的用法
Browse files Browse the repository at this point in the history
  • Loading branch information
hisenyuan committed Jul 16, 2018
1 parent 2f9e645 commit c8afde2
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions src/main/java/com/hisen/thread/TestThreadPoolExample.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package com.hisen.thread;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.log4j.Logger;
import org.junit.Test;

import java.util.concurrent.*;

public class TestThreadPoolExample {
private static org.apache.log4j.Logger LOGGER = Logger.getRootLogger();

@Test
public void testThreadExample() {
ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("hisenyuan").build();
ExecutorService pool = new ThreadPoolExecutor(
20,
50,
10000L,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(10240),
namedThreadFactory,
new ThreadPoolExecutor.AbortPolicy());
for (int i = 0; i < 50; i++) {
// submit your executor
pool.execute(this::printInfo);
}
pool.shutdown();
try {
while (!pool.awaitTermination(500, TimeUnit.MILLISECONDS)) {
LOGGER.debug("Waiting for terminate");
}
} catch (InterruptedException e) {
LOGGER.error(e);
}
}

/**
* something you want to deal
*/
void printInfo() {
for (int i = 0; i < 100; i++) {
Thread t = Thread.currentThread();
LOGGER.info(t.getId() + "\t" + t.getName() + "\t" + t.getState() + "\t" + System.nanoTime());
}
}
}

0 comments on commit c8afde2

Please sign in to comment.