Runnable
public class ThreadPool implements Runnable {
private int i;
public ThreadPool() {}
public ThreadPool(int i) {
this.i = i;
}
@Override
public void run() {
System.out.println("***************start run**************" + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("***************end run****************" + i + " " + this.toString());
}
}
Thread
public class ThreadExtend extends Thread {
@Override
public void run() {
System.out.println("---------" + getName() + "----------");
}
}
Lambda
Thread thread = new Thread(() -> System.out.println("------- runnable -------"));
Callable
public class ThreadCallable implements Callable<String> {
@Override
public String call() {
String threadName = Thread.currentThread().getName();
System.out.println("---------" + threadName + "----------");
return threadName;
}
public static void main(String[] args) {
ThreadCallable callable = new ThreadCallable();
FutureTask<String> futureTask = new FutureTask<>(callable);
Thread thread = new Thread(futureTask);
try {
thread.start();
System.out.println(futureTask.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
Executors
import haut.zm.thread.factory.MyThreadFactory;
import haut.zm.thread.implement.ThreadPool;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadExecutorsMain {
private static ExecutorService executorSingle = Executors.newSingleThreadExecutor();
private static ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 4, 20, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new MyThreadFactory("test"));
private static ExecutorService executorFixed = Executors.newFixedThreadPool(2);
private static ExecutorService executorCached = Executors.newCachedThreadPool();
private static ExecutorService executorScheduled = Executors.newScheduledThreadPool(2);
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 4; i++) {
executorFixed.execute(new ThreadPool(i));
}
Thread.sleep(10000);
for (int i = 0; i < 4; i++) {
executorCached.execute(new ThreadPool(i));
}
Thread.sleep(10000);
for (int i = 0; i < 4; i++) {
executorSingle.execute(new ThreadPool(i));
}
Thread.sleep(10000);
for (int i = 0; i < 4; i++) {
executorScheduled.execute(new ThreadPool(i));
}
Thread.sleep(10000);
for (int i = 0; i < 4; i++) {
threadPoolExecutor.execute(new ThreadPool(i));
}
while (true) {
AtomicInteger i = new AtomicInteger(0);
executorCached.submit(i::getAndIncrement);
}
}
}