在Java并发编程中,线程(Threads)是实现多任务并发执行的基础。以下是线程实践的基本步骤,包括如何创建、启动和管理线程。
1. 创建线程
创建线程的两种常见方法是继承Thread
类或实现Runnable
接口。
通过继承Thread
类
public class MyThread extends Thread {
@Override
public void run() {
// 执行任务的代码
System.out.println("Thread running: " + this.getName());
}
}
通过实现Runnable
接口
public class MyRunnable implements Runnable {
@Override
public void run() {
// 执行任务的代码
System.out.println("Runnable running");
}
}
2. 启动线程
创建了线程或Runnable
实例后,可以通过线程实例的start()
方法来启动线程。
启动继承自Thread
的线程
MyThread thread = new MyThread();
thread.start(); // 启动线程
启动实现了Runnable
接口的线程
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start(); // 启动线程
3. 管理线程
线程管理涉及线程的生命周期,包括线程的创建、启动、运行、等待、通知和终止。
线程睡眠(Sleeping)
使当前运行的线程暂停执行一段时间。
try {
Thread.sleep(1000); // 使线程睡眠1秒钟
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // 重新设置中断状态
// 处理中断逻辑
}
等待其他线程(Joining)
等待另一个线程完成其执行。
Thread thread = new Thread(new MyRunnable());
thread.start();
try {
thread.join(); // 等待线程thread完成
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
// 处理中断逻辑
}
线程中断(Interrupting)
设置线程的中断状态。interrupt()
方法用来中断线程,而线程可以通过检查中断状态来相应地停止任务。
Thread thread = new Thread(new MyRunnable());
thread.start();
// 在某个时刻中断线程
thread.interrupt();
在MyRunnable
的run
方法内部,你可能需要检查中断状态:
public class MyRunnable implements Runnable {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
// 执行任务代码
}
// 清理资源和退出
}
}
4. 同步(Synchronization)
在多线程环境中,当多个线程试图访问共享资源时,需要确保资源的同步访问,以防止数据不一致。
使用synchronized
关键字
public class SharedResource {
private int count = 0;
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
SharedResource resource = new SharedResource();
// 使用资源的线程,确保访问是同步的
5. 优雅地停止线程
在Java中,推荐的停止线程的方式是设置一个标志或者使用interrupt()
方法,并在线程的run
方法中适当地检查这个标志或响应中断。
public class GracefulShutdownThread implements Runnable {
private volatile boolean shutdownRequested = false;
public void run() {
while (!shutdownRequested) {
// 执行任务
}
// 执行清理操作
}
public void shutdown() {
shutdownRequested = true;
}
}
// 使用示例
GracefulShutdownThread task = new GracefulShutdownThread();
Thread thread = new Thread(task);
thread.start();
// 当需要停止线程时
task.shutdown();
线程是Java并发编程的核心,确保正确地使用线程和管理它们的生命周期对于编写并发程序非常重要。以下是一些高级的线程实践和概念,它们可以帮助你更好地使用线程并解决并发编程中的常见问题。
线程优先级
线程可以拥有不同的优先级。优先级较高的线程理论上应该获得更多的执行时间,但这通常依赖于操作系统的调度策略。
Thread thread = new Thread(new MyRunnable());
thread.setPriority(Thread.MAX_PRIORITY);
thread.start();
守护线程(Daemon Threads)
守护线程是一种在后台提供通用服务的线程(例如,垃圾回收器),并且当所有非守护线程都结束时,守护线程会自动退出。
Thread thread = new Thread(new MyRunnable());
thread.setDaemon(true); // 设置为守护线程
thread.start();
线程局部变量(Thread-Local Variables)
ThreadLocal
类提供了线程局部变量,每个线程都有该变量的独立副本。
ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
public class MyRunnable implements Runnable {
@Override
public void run() {
threadLocal.set((int) (Math.random() * 100D));
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println(threadLocal.get());
}
}
处理线程异常
未捕获的异常会导致线程终止。你可以通过设置未捕获异常处理器来处理这些异常。
Thread thread = new Thread(new MyRunnable());
thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
System.out.println("An exception has been captured in thread: " + t.getName());
System.out.println("Exception: " + e.getClass().getName() + ": " + e.getMessage());
}
});
thread.start();