多线程示例
下文笔者将通过示例的方式,讲述一个多线程的示例,如下所示
1.基本多线程示例
使用`Thread`类创建线程 class MyThread extends Thread { @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName() + " - " + i); try { Thread.sleep(1000); // 休眠1秒 } catch (InterruptedException e) { e.printStackTrace(); } } } } public class ThreadExample { public static void main(String[] args) { MyThread thread1 = new MyThread(); MyThread thread2 = new MyThread(); thread1.start(); thread2.start(); } }
输出信息 Thread-0 - 0 Thread-1 - 0 Thread-0 - 1 Thread-1 - 1 Thread-0 - 2 Thread-1 - 2 Thread-0 - 3 Thread-1 - 3 Thread-0 - 4 Thread-1 - 4
使用`Runnable`接口创建线程
class MyRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " - " + i);
try {
Thread.sleep(1000); // 休眠1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class RunnableExample {
public static void main(String[] args) {
Thread thread1 = new Thread(new MyRunnable());
Thread thread2 = new Thread(new MyRunnable());
thread1.start();
thread2.start();
}
}
输出以下信息 Thread-0 - 0 Thread-1 - 0 Thread-0 - 1 Thread-1 - 1 Thread-0 - 2 Thread-1 - 2 Thread-0 - 3 Thread-1 - 3 Thread-0 - 4 Thread-1 - 4
2.线程同步示例
使用`synchronized`关键字
class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
class CounterThread extends Thread {
private Counter counter;
public CounterThread(Counter counter) {
this.counter = counter;
}
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
}
}
public class SynchronizedExample {
public static void main(String[] args) {
Counter counter = new Counter();
Thread thread1 = new Thread(new CounterThread(counter));
Thread thread2 = new Thread(new CounterThread(counter));
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Final count: " + counter.getCount());
}
}
输出以下信息 Final count: 2000
3.线程池示例
使用`ExecutorService`
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
class Task implements Runnable {
private String name;
public Task(String name) {
this.name = name;
}
@Override
public void run() {
System.out.println("Task " + name + " started by " + Thread.currentThread().getName());
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Task " + name + " completed by " + Thread.currentThread().getName());
}
}
public class ThreadPoolExample {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
for (int i = 0; i < 10; i++) {
executorService.submit(new Task("Task-" + i));
}
executorService.shutdown();
try {
executorService.awaitTermination(1, TimeUnit.MINUTES);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("All tasks completed");
}
}
输出以下信息 Task Task-0 started by pool-1-thread-1 Task Task-1 started by pool-1-thread-2 Task Task-2 started by pool-1-thread-3 Task Task-3 started by pool-1-thread-1 Task Task-4 started by pool-1-thread-2 Task Task-5 started by pool-1-thread-3 Task Task-6 started by pool-1-thread-1 Task Task-7 started by pool-1-thread-2 Task Task-8 started by pool-1-thread-3 Task Task-9 started by pool-1-thread-1 Task Task-0 completed by pool-1-thread-1 Task Task-1 completed by pool-1-thread-2 Task Task-2 completed by pool-1-thread-3 Task Task-3 completed by pool-1-thread-1 Task Task-4 completed by pool-1-thread-2 Task Task-5 completed by pool-1-thread-3 Task Task-6 completed by pool-1-thread-1 Task Task-7 completed by pool-1-thread-2 Task Task-8 completed by pool-1-thread-3 Task Task-9 completed by pool-1-thread-1 All tasks completed
4.使用`Callable`和`Future`
import java.util.concurrent.*;
class MyCallable implements Callable<Integer> {
private int number;
public MyCallable(int number) {
this.number = number;
}
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = 1; i <= number; i++) {
sum += i;
}
return sum;
}
}
public class CallableExample {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
Future<Integer> future1 = executorService.submit(new MyCallable(10));
Future<Integer> future2 = executorService.submit(new MyCallable(20));
try {
int result1 = future1.get();
int result2 = future2.get();
System.out.println("Result 1: " + result1);
System.out.println("Result 2: " + result2);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
executorService.shutdown();
}
}
输出以下信息 Result 1: 55 Result 2: 210
5.使用`CountDownLatch`
import java.util.concurrent.CountDownLatch;
class Worker implements Runnable {
private CountDownLatch latch;
public Worker(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is working...");
try {
Thread.sleep(2000); // 模拟工作时间
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " finished work.");
latch.countDown();
}
}
public class CountDownLatchExample {
public static void main(String[] args) {
int numberOfThreads = 3;
CountDownLatch latch = new CountDownLatch(numberOfThreads);
for (int i = 0; i < numberOfThreads; i++) {
Thread thread = new Thread(new Worker(latch));
thread.start();
}
try {
latch.await(); // 主线程等待所有工作线程完成
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("All workers have finished their work.");
}
}
输出以下信息 Thread-0 is working... Thread-1 is working... Thread-2 is working... Thread-0 finished work. Thread-1 finished work. Thread-2 finished work. All workers have finished their work.
6.使用`Semaphore`
import java.util.concurrent.Semaphore;
class PrintQueue {
private final Semaphore semaphore;
public PrintQueue() {
semaphore = new Semaphore(2); // 允许最多2个线程同时访问
}
public void printJob(Object document) {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + " is printing a job.");
Thread.sleep(2000); // 模拟打印时间
System.out.println(Thread.currentThread().getName() + " finished printing.");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}
}
class PrinterJob implements Runnable {
private PrintQueue printQueue;
public PrinterJob(PrintQueue printQueue) {
this.printQueue = printQueue;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is going to print a job.");
printQueue.printJob(new Object());
}
}
public class SemaphoreExample {
public static void main(String[] args) {
PrintQueue printQueue = new PrintQueue();
for (int i = 0; i < 5; i++) {
Thread thread = new Thread(new PrinterJob(printQueue));
thread.start();
}
}
}
运行以上代码,将输出以下信息 Thread-0 is going to print a job. Thread-1 is going to print a job. Thread-2 is going to print a job. Thread-3 is going to print a job. Thread-4 is going to print a job. Thread-0 is printing a job. Thread-1 is printing a job. Thread-0 finished printing. Thread-2 is printing a job. Thread-1 finished printing. Thread-3 is printing a job. Thread-2 finished printing. Thread-4 is printing a job. Thread-3 finished printing. Thread-4 finished printing.
7.使用`ReentrantLock`
import java.util.concurrent.locks.ReentrantLock;
class Counter {
private int count = 0;
private final ReentrantLock lock = new ReentrantLock();
public void increment() {
lock.lock();
try {
count++;
} finally {
lock.unlock();
}
}
public int getCount() {
lock.lock();
try {
return count;
} finally {
lock.unlock();
}
}
}
class CounterThread implements Runnable {
private Counter counter;
public CounterThread(Counter counter) {
this.counter = counter;
}
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
}
}
public class ReentrantLockExample {
public static void main(String[] args) {
Counter counter = new Counter();
Thread thread1 = new Thread(new CounterThread(counter));
Thread thread2 = new Thread(new CounterThread(counter));
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Final count: " + counter.getCount());
}
}
运行以上代码,将输出以下信息 Final count: 2000
8.使用`CompletableFuture`
import java.util.concurrent.CompletableFuture;
public class CompletableFutureExample {
public static void main(String[] args) {
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
System.out.println("Task started by " + Thread.currentThread().getName());
try {
Thread.sleep(2000); // 模拟任务时间
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Task completed by " + Thread.currentThread().getName();
});
future.thenAccept(result -> {
System.out.println(result);
});
System.out.println("Main thread continues...");
try {
Thread.sleep(3000); // 等待任务完成
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Main thread finished.");
}
}
运行以上代码,将输出以下信息 Main thread continues... Task started by ForkJoinPool.commonPool-worker-1 Task completed by ForkJoinPool.commonPool-worker-1 Main thread finished.
9.使用`ExecutorCompletionService`
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.Future;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
public class ExecutorCompletionServiceExample {
public static void main(String[] args) {
// 创建一个固定大小的线程池
ExecutorService executorService = Executors.newFixedThreadPool(3);
// 创建 ExecutorCompletionService 实例
ExecutorCompletionService completionService = new ExecutorCompletionService<>(executorService);
// 提交任务
for (int i = 0; i < 5; i++) {
final int taskId = i;
completionService.submit(new Callable() {
@Override
public String call() throws Exception {
// 模拟任务执行时间
Thread.sleep((taskId + 1) * 1000);
return "Task " + taskId + " completed";
}
});
}
// 获取任务结果
for (int i = 0; i < 5; i++) {
try {
Future future = completionService.take();
String result = future.get();
System.out.println(result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
// 关闭线程池
executorService.shutdown();
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


