单线程
1.实现Runnable接口
public class RunnableTest implements Runnable {
public static void main(String[] args) {
RunnableTest t = new RunnableTest();
new Thread(t, "a--").start();
}
@Override
public void run() {
System.out.println("RunnableTest");
}
}
2.继承Thread
public class ThreadTest extends Thread {
public ThreadTest(String s) {
super(s);
}
public static void main(String[] args) {
new ThreadTest("a--").start();
}
public void run() {
System.out.println("ThreadTest");
}
}
线程池
1.ThreadPoolExecutor基础的线程池
public class ThreadPoolExecutorTest {
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 20, 20, TimeUnit.SECONDS, new LinkedBlockingQueue<>(500));
}
}
2.ScheduledThreadPoolExecutor定时任务线程池
public class ScheduledThreadPoolExecutorTest {
public static void main(String[] args) {
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
executor.scheduleAtFixedRate(() ->
{
System.out.println(2);
}, 1, 2, TimeUnit.SECONDS);//第一次1s,周期2s
}
}
3.ThreadPoolTaskExecutor线程池由spring提供
@Configuration
@EnableAsync
public class ThreadPoolTaskExecutorConfig {
@Bean("taskExecutor")
public Executor taskExecutro() {
ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
taskExecutor.setCorePoolSize(10);
taskExecutor.setMaxPoolSize(50);
taskExecutor.setQueueCapacity(200);
taskExecutor.setKeepAliveSeconds(60);
taskExecutor.setThreadNamePrefix("taskExecutor:");
taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
taskExecutor.setAwaitTerminationSeconds(60);
taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
taskExecutor.initialize();
return taskExecutor;
}
}
多线程
1.CountDownLatch阻塞直到最慢的线程执行完成
public class CountDownLatchTest {
public static void main(String[] args) throws InterruptedException {
List<Object> list = new ArrayList<>();
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 20, 20, TimeUnit.SECONDS, new LinkedBlockingQueue<>(500));
CountDownLatch countDownLatch = new CountDownLatch(2);
threadPoolExecutor.execute(() -> {
try {
list.add("test1");
} catch (Exception e) {
e.printStackTrace();
} finally {
countDownLatch.countDown();
}
});
threadPoolExecutor.execute(() -> {
try {
list.add("test2");
} catch (Exception e) {
e.printStackTrace();
} finally {
countDownLatch.countDown();
}
});
countDownLatch.await(3, TimeUnit.SECONDS);
threadPoolExecutor.shutdown();
System.out.println(list);
}
}
2.Semaphore每次指定几个线程完成任务
public class SemaphoreTest {
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 20, 20, TimeUnit.SECONDS, new LinkedBlockingQueue<>(500));
Semaphore semaphore = new Semaphore(2);
for (int i = 0; i < 5; i++) {
threadPoolExecutor.execute(() -> {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + ":aquire() at time:" + System.currentTimeMillis());
Thread.sleep(1000);
semaphore.release();
} catch (Exception e) {
e.printStackTrace();
}
});
}
}
}
3.CyclicBarrier在指定的线程数量完成后执行run方法
public class CyclicBarrierTest {
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 20, 20, TimeUnit.SECONDS, new LinkedBlockingQueue<>(500));
final CyclicBarrier cb = new CyclicBarrier(3, new Runnable() {
@Override
public void run() {
System.out.println("执行CyclicBarrier方法");
}
});
for (int i = 1; i < 5; i++) {
threadPoolExecutor.execute(() -> {
try {
String name = Thread.currentThread().getName();
Thread.sleep(1000);
System.out.println("线程" + name + "即将到达集合地点1,当前已有" + cb.getNumberWaiting() + "个已经到达,正在等候");
cb.await();//到此如果没有达到公共屏障点,则该线程处于等待状态,如果达到公共屏障点则所有处于等待的线程都继续往下运行
Thread.sleep(1000);
System.out.println("线程" + name + "即将到达集合地点2,当前已有" + cb.getNumberWaiting() + "个已经到达,正在等候");
cb.await(); //这里CyclicBarrier对象又可以重用
Thread.sleep(1000);
System.out.println("线程" + name + "即将到达集合地点3,当前已有" + cb.getNumberWaiting() + "个已经到达,正在等候");
cb.await();
} catch (Exception e) {
e.printStackTrace();
}
});
}
threadPoolExecutor.shutdown();
System.out.println("结束");
}
}
其他
1.Exchanger交换两个线程数据
public class ExchangerTest {
public static void main(String[] args) {
// 创建一个Exchanger对象,用于交换数据
Exchanger<String> exchanger = new Exchanger<>();
// 创建并启动第一个线程,它将携带数据"Data from Thread 1"进行交换
Thread producer = new Thread(() -> {
try {
String producedData = "Data from Thread 1";
String consumerData = exchanger.exchange(producedData);
System.out.println("Thread 1 received: " + consumerData);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("Thread 1 was interrupted");
}
});
// 创建并启动第二个线程,它将携带数据"Data from Thread 2"进行交换
Thread consumer = new Thread(() -> {
try {
String producedData = "Data from Thread 2";
// 为了让示例更清晰,让第二个线程稍微延迟一会儿,确保第一个线程先到达交换点
Thread.sleep(100);
String producerData = exchanger.exchange(producedData);
System.out.println("Thread 2 received: " + producerData);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("Thread 2 was interrupted");
}
});
// 启动线程
producer.start();
consumer.start();
}
}
2.Callable获取线程返回值
public class CallableTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 20, 20, TimeUnit.SECONDS, new LinkedBlockingQueue<>(500));
List<Future> list = new ArrayList<>();
for (int i = 0; i < 5; i++) {
Callable callable = new Callable() {
@Override
public Object call() throws Exception {
return new Date().toLocaleString();
}
};
// 执行任务并获取Future对象
Future f = threadPoolExecutor.submit(callable);
list.add(f);
}
threadPoolExecutor.shutdown();
// 获取所有并发任务的运行结果
for (Future f : list) {
// 从Future对象上获取任务的返回值,并输出到控制台
System.out.println("Future" + f.get().toString());
}
}
}