【JAVA】线程详解 线程详解

线程的基本概念

  • 在Java中,线程(Thread)是并发编程的基本单元。线程允许一个程序执行多个任务(代码路径),从而提高效率和响应性。下面是对Java线程的详细介绍,包括概念、实现方法、线程的生命周期、常见的线程管理工具和最佳实践等。

1. 线程的基本概念

  • 进程与线程:
    • 进程是操作系统中执行的一个程序实例,拥有独立的内存空间。
    • 线程是进程中的一个执行单元,一个进程可以包含多个线程,这些线程共享进程的内存空间和资源。
  • 多线程的意义:
    • 并发:多线程可以让程序执行多个任务,提高应用程序的性能,尤其是在I/O密集型任务中,如文件读取、网络请求等。
    • 并行:在多核处理器上,多个线程可以同时在不同的CPU核心上运行,实现真正的并行处理。

2. 创建线程的两种方式

2.1 继承Thread类

通过继承Thread类并重写run()方法来定义线程,然后调用start()方法启动线程。

示例代码:

class MyThread extends Thread {
 @Override
 public void run() {
 System.out.println("Thread is running.");
 }
}
public class Main {
 public static void main(String[] args) {
 MyThread thread = new MyThread();
 thread.start(); // 启动线程,run()方法将被执行
 }
}

2.2 实现Runnable接口

通过实现Runnable接口的run()方法,然后将其传递给Thread对象并调用start()方法启动线程。这种方式更为灵活,因为它允许类继承其他类,同时实现多线程。

示例代码:

class MyRunnable implements Runnable {
 @Override
 public void run() {
 System.out.println("Runnable is running.");
 }
}
public class Main {
 public static void main(String[] args) {
 Thread thread = new Thread(new MyRunnable());
 thread.start(); // 启动线程,run()方法将被执行
 }
}

3. 线程的生命周期

Java中的线程在运行时经历不同的状态,每个状态都有特定的意义和作用。

  • 新建状态(New):线程对象被创建,但还未启动。
  • 就绪状态(Runnable):线程已经启动,等待CPU分配时间片执行。
  • 运行状态(Running):线程获得CPU时间片,正在执行run()方法中的代码。
  • 阻塞状态(Blocked/Waiting/Timed Waiting):线程因某种原因被阻塞,等待某个条件的满足(如等- 待锁释放、计时器到期等)。
  • 终止状态(Terminated):线程的run()方法执行完毕或因未捕获的异常而终止。

4. 线程的常见操作

4.1 线程休眠(sleep())

Thread.sleep(milliseconds)方法使当前线程暂停执行一段时间,但不释放锁。

示例代码:

public class Main {
 public static void main(String[] args) {
 try {
 System.out.println("Thread sleeping...");
 Thread.sleep(2000); // 线程休眠2秒
 System.out.println("Thread woke up.");
 } catch (InterruptedException e) {
 e.printStackTrace();
 }
 }
}

4.2 线程等待(join())

join()方法在Java中用于线程间的协调和等待。它使一个线程等待另一个线程完成执行后才继续执行

示例代码:

class MyThread extends Thread {
 @Override
 public void run() {
 for (int i = 0; i < 5; i++) {
 System.out.println("Thread is running: " + i);
 try {
 Thread.sleep(1000);
 } catch (InterruptedException e) {
 e.printStackTrace();
 }
 }
 }
}
public class Main {
 public static void main(String[] args) {
 MyThread thread = new MyThread();
 thread.start(); // 启动线程
 try {
 thread.join(); // 主线程等待thread线程结束
 } catch (InterruptedException e) {
 e.printStackTrace();
 }
 System.out.println("Thread has finished, main thread resumes.");
 }
}

解释:

  • thread.join()使得主线程在thread线程执行完之前不会继续执行。
  • 主线程在thread线程的run()方法执行完成后,才会继续执行System.out.println(“Thread has finished, main thread resumes.”);。

4.3 线程中断(interrupt())

interrupt()方法用于中断线程的执行,通常与InterruptedException结合使用。

示例代码:

class MyRunnable implements Runnable {
 @Override
 public void run() {
 try {
 while (!Thread.currentThread().isInterrupted()) {
 System.out.println("Thread running...");
 Thread.sleep(1000);
 }
 } catch (InterruptedException e) {
 System.out.println("Thread was interrupted.");
 }
 }
}
public class Main {
 public static void main(String[] args) throws InterruptedException {
 Thread thread = new Thread(new MyRunnable());
 thread.start();
 Thread.sleep(3000);
 thread.interrupt(); // 中断线程
 }
}

4.4 线程优先级(setPriority())

线程的优先级决定了线程获得CPU时间片的机会大小。Java线程优先级范围从Thread.MIN_PRIORITY(1)到Thread.MAX_PRIORITY(10),默认优先级为Thread.NORM_PRIORITY(5)。

示例代码:

Thread thread = new Thread(new MyRunnable());
thread.setPriority(Thread.MAX_PRIORITY); // 设置最高优先级
thread.start();

5. 线程同步与互斥

在多线程环境中,多个线程可能同时访问共享资源,为了避免数据不一致,需要对共享资源的访问进行同步控制。

5.1 同步块(synchronized)

synchronized关键字用于锁定一个方法或代码块,使得同一时间只有一个线程可以执行该方法或代码块。

示例代码:

class Counter {
 private int count = 0;
 public synchronized void increment() {
 count++;
 }
 public int getCount() {
 return count;
 }
}
public class Main {
 public static void main(String[] args) {
 Counter counter = new Counter();
 Thread t1 = new Thread(() -> {
 for (int i = 0; i < 1000; i++) {
 counter.increment();
 }
 });
 Thread t2 = new Thread(() -> {
 for (int i = 0; i < 1000; i++) {
 counter.increment();
 }
 });
 t1.start();
 t2.start();
 try {
 t1.join();
 t2.join();
 } catch (InterruptedException e) {
 e.printStackTrace();
 }
 System.out.println("Final count: " + counter.getCount());
 }
}

5.2 线程通信(wait() 和 notify())

wait()和notify()/notifyAll()方法用于线程间的通信,通常与synchronized关键字结合使用,用来协调线程之间的合作。

示例代码:

class SharedResource {
 private boolean available = false;
 public synchronized void produce() {
 while (available) {
 try {
 wait();
 } catch (InterruptedException e) {
 e.printStackTrace();
 }
 }
 available = true;
 System.out.println("Produced resource.");
 notify();
 }
 public synchronized void consume() {
 while (!available) {
 try {
 wait();
 } catch (InterruptedException e) {
 e.printStackTrace();
 }
 }
 available = false;
 System.out.println("Consumed resource.");
 notify();
 }
}
public class Main {
 public static void main(String[] args) {
 SharedResource resource = new SharedResource();
 Thread producer = new Thread(() -> {
 for (int i = 0; i < 10; i++) {
 resource.produce();
 }
 });
 Thread consumer = new Thread(() -> {
 for (int i = 0; i < 10; i++) {
 resource.consume();
 }
 });
 producer.start();
 consumer.start();
 }
}

6. 高级线程管理工具

6.1 ExecutorService

ExecutorService是Java并发库提供的一个高级线程池管理工具,允许开发者管理和复用线程。

示例代码:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
 public static void main(String[] args) {
 ExecutorService executor = Executors.newFixedThreadPool(2);
 executor.submit(() -> {
 System.out.println("Task 1");
 });
 executor.submit(() -> {
 System.out.println("Task 2");
 });
 executor.shutdown();
 }
}

6.2 ForkJoinPool

ForkJoinPool是Java 7引入的一个并行处理框架,特别适合处理大规模的任务分解与并行执行。

import java.util.concurrent.RecursiveTask;
import java.util.concurrent.ForkJoinPool;
class SumTask extends RecursiveTask {
 private final int[] arr;
 private final int start;
 private final int end;
 public SumTask(int[] arr, int start, int end) {
 this.arr = arr;
 this.start = start;
 this.end = end;
 }
 @Override
 protected Integer compute() {
 if (end - start 

7. 总结

  • 线程创建:可以通过继承Thread类或实现Runnable接口来创建线程。
  • 线程生命周期:包括新建、就绪、运行、阻塞和终止状态。
  • 线程操作:包括线程休眠、线程中断和线程优先级的设置。
  • 线程同步:使用synchronized关键字来避免多个线程访问共享资源时产生冲突。
  • 线程通信:通过wait()和notify()等方法来实现线程间的协作。
  • 高级线程管理:ExecutorService和ForkJoinPool提供了更高级的线程管理和并行处理能力。

理解这些基本概念和操作是掌握Java多线程编程的基础,有助于提高程序的并发性和性能。

作者:弗瑞德学JAVA原文地址:https://blog.csdn.net/weixin_37559642/article/details/141234073

%s 个评论

要回复文章请先登录注册