Java多线程技术详解及案例
本文详细介绍了Java中的多线程技术,包括基本概念、线程创建方式、线程同步与通信、线程池等,并附带案例讲解。
1. 多线程基本概念
多线程是Java并发编程的基础。它允许一个程序同时执行多个线程,每个线程完成一定的任务。多线程可以提高程序的运行效率和响应速度。
2. 线程的创建方式
Java中线程的创建主要有三种方式:继承Thread类、实现Runnable接口、使用Callable和Future。
2.1 继承Thread类
通过继承Thread类并重写其run方法,可以创建一个线程。
class MyThread extends Thread {
public void run() {
System.out.println("MyThread is running");
}
}
public class Main {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
2.2 实现Runnable接口
实现Runnable接口并将其实例作为Thread对象的target来创建线程。
class MyRunnable implements Runnable {
public void run() {
System.out.println("MyRunnable is running");
}
}
public class Main {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
2.3 使用Callable和Future
Callable接口类似于Runnable接口,但它可以返回值并且可以抛出异常。Future对象用于获取Callable任务执行的结果。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
class MyCallable implements Callable {
public String call() throws Exception {
return "MyCallable result";
}
}
public class Main {
public static void main(String[] args) {
MyCallable myCallable = new MyCallable();
FutureTask futureTask = new FutureTask(myCallable);
Thread thread = new Thread(futureTask);
thread.start();
try {
String result = futureTask.get();
System.out.println(result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
3. 线程同步与通信
多线程编程中,线程同步和通信是非常重要的概念。它们用于解决多个线程同时访问共享资源时的数据一致性问题。
3.1 synchronized关键字
synchronized关键字可以用于方法或代码块,以实现线程同步。
public class SynchronizedExample {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
3.2 wait和notify/notifyAll方法
wait方法使线程等待,notify/notifyAll方法唤醒等待的线程。
class WaitNotifyExample {
private final Object lock = new Object();
private boolean flag = false;
public void waitThread() {
synchronized (lock) {
while (!flag) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("WaitThread is running");
}
}
public void notifyThread() {
synchronized (lock) {
flag = true;
lock.notify();
}
}
}
public class Main {
public static void main(String[] args) {
WaitNotifyExample example = new WaitNotifyExample();
Thread t1 = new Thread(example::waitThread);
Thread t2 = new Thread(example::notifyThread);
t1.start();
try {
Thread.sleep(1000); // 确保t1先运行并等待
} catch (InterruptedException e) {
e.printStackTrace();
}
t2.start();
}
4. 线程池
线程池是一种多线程处理形式,处理大量异步任务时,可以避免频繁创建和销毁线程所带来的性能损耗。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolExample {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(3);
for (int i = 0; i {
System.out.println(Thread.currentThread().getName() + " is running");
});
}
executorService.shutdown();
}