boxmoe_header_banner_img

Hello! 欢迎来到悠悠畅享网!

文章导读

java使用教程怎样创建和启动多线程 java使用教程的多线程编程操作技巧​


avatar
站长 2025年8月14日 3

Java中创建多线程推荐实现Runnable接口,因其避免单继承限制且更灵活;通过start()启动线程,直接调用run()不创建新线程;控制执行顺序可用join()、wait()/notify()、CountDownLatch等;避免死锁需按序获取锁、使用定时锁或资源排序;线程池大小应根据CPU核心数、任务类型(CPU或IO密集型)合理设置,通常IO密集型设为CPU核心数的2倍,并通过ExecutorService管理线程池。

java使用教程怎样创建和启动多线程 java使用教程的多线程编程操作技巧​

在Java中,创建和启动多线程主要有两种方式:继承Thread类和实现Runnable接口。选择哪种方式取决于你的具体需求,但通常推荐使用实现Runnable接口的方式,因为它更灵活,避免了Java单继承的限制。

解决方案

  1. 继承Thread类:

    • 创建一个继承自
      Thread

      的类。

    • 重写
      run()

      方法,将线程要执行的任务代码放在

      run()

      方法中。

    • 创建
      Thread

      类的实例。

    • 调用
      start()

      方法启动线程。

    class MyThread extends Thread {     @Override     public void run() {         System.out.println("Thread running: " + Thread.currentThread().getName());     } }  public class Main {     public static void main(String[] args) {         MyThread thread1 = new MyThread();         thread1.start(); // 启动线程,而不是直接调用run()     } }

    直接调用

    run()

    方法,其实只是在当前线程(main线程)中执行了

    run()

    方法里的代码,并没有创建新的线程。 必须调用

    start()

    方法,才能真正启动一个新的线程,并执行

    run()

    方法。

    立即学习Java免费学习笔记(深入)”;

  2. 实现Runnable接口:

    • 创建一个类,实现
      Runnable

      接口。

    • 实现
      run()

      方法,将线程要执行的任务代码放在

      run()

      方法中。

    • 创建
      Runnable

      接口的实现类的实例。

    • 创建一个
      Thread

      类的实例,并将

      Runnable

      接口的实现类的实例作为参数传递给

      Thread

      类的构造方法。

    • 调用
      Thread

      类的

      start()

      方法启动线程。

    class MyRunnable implements Runnable {     @Override     public void run() {         System.out.println("Thread running: " + Thread.currentThread().getName());     } }  public class Main {     public static void main(String[] args) {         MyRunnable runnable = new MyRunnable();         Thread thread2 = new Thread(runnable);         thread2.start();     } }

    使用

    Runnable

    接口的方式,可以将线程的任务代码和线程的创建分离,更符合面向对象的设计原则。

如何控制多线程的执行顺序?

控制多线程的执行顺序是一个常见的问题,Java提供了多种机制来实现,例如

join()

,

wait()

,

notify()

,

notifyAll()

,

CountDownLatch

,

CyclicBarrier

,

Semaphore

等。

  • join()

    方法: 可以使一个线程等待另一个线程执行完毕。例如,线程A调用线程B的

    join()

    方法,那么线程A会等待线程B执行完毕后再继续执行。

    public class Main {     public static void main(String[] args) throws InterruptedException {         Thread thread1 = new Thread(() -> {             System.out.println("Thread 1 started");             try {                 Thread.sleep(1000); // 模拟耗时操作             } catch (InterruptedException e) {                 e.printStackTrace();             }             System.out.println("Thread 1 finished");         });          Thread thread2 = new Thread(() -> {             System.out.println("Thread 2 started");             try {                 thread1.join(); // 等待thread1执行完毕             } catch (InterruptedException e) {                 e.printStackTrace();             }             System.out.println("Thread 2 finished");         });          thread1.start();         thread2.start();     } }

    在这个例子中,

    thread2

    会等待

    thread1

    执行完毕后再开始执行。

  • wait()

    ,

    notify()

    ,

    notifyAll()

    方法: 这些方法是Object类的方法,用于线程间的通信和同步。

    wait()

    使线程进入等待状态,直到被

    notify()

    notifyAll()

    唤醒。

    notify()

    唤醒一个等待的线程,

    notifyAll()

    唤醒所有等待的线程。 这些方法必须在

    synchronized

    块中使用。

    public class Main {     private static final Object lock = new Object();     private static boolean flag = false;      public static void main(String[] args) {         Thread thread1 = new Thread(() -> {             synchronized (lock) {                 System.out.println("Thread 1 started");                 try {                     while (!flag) {                         lock.wait(); // 等待flag变为true                     }                 } catch (InterruptedException e) {                     e.printStackTrace();                 }                 System.out.println("Thread 1 finished");             }         });          Thread thread2 = new Thread(() -> {             synchronized (lock) {                 System.out.println("Thread 2 started");                 flag = true;                 lock.notify(); // 唤醒等待的线程                 System.out.println("Thread 2 finished");             }         });          thread1.start();         try {             Thread.sleep(100); // 确保thread1先启动         } catch (InterruptedException e) {             e.printStackTrace();         }         thread2.start();     } }

    在这个例子中,

    thread1

    会等待

    thread2

    设置

    flag

    true

    并唤醒它。

  • CountDownLatch

    :

    CountDownLatch

    允许一个或多个线程等待其他线程完成操作。它维护了一个计数器,计数器初始化为一个正整数。 每当一个线程完成任务后,计数器的值就会减1。 当计数器的值为0时,所有等待的线程都会被释放。

    import java.util.concurrent.CountDownLatch;  public class Main {     public static void main(String[] args) throws InterruptedException {         CountDownLatch latch = new CountDownLatch(2); // 初始化计数器为2          Thread thread1 = new Thread(() -> {             System.out.println("Thread 1 started");             try {                 Thread.sleep(1000);             } catch (InterruptedException e) {                 e.printStackTrace();             }             System.out.println("Thread 1 finished");             latch.countDown(); // 计数器减1         });          Thread thread2 = new Thread(() -> {             System.out.println("Thread 2 started");             try {                 Thread.sleep(500);             } catch (InterruptedException e) {                 e.printStackTrace();             }             System.out.println("Thread 2 finished");             latch.countDown(); // 计数器减1         });          Thread thread3 = new Thread(() -> {             try {                 latch.await(); // 等待计数器变为0             } catch (InterruptedException e) {                 e.printStackTrace();             }             System.out.println("Thread 3 started after Thread 1 and Thread 2 finished");         });          thread1.start();         thread2.start();         thread3.start();     } }

    在这个例子中,

    thread3

    会等待

    thread1

    thread2

    都执行完毕后再开始执行。

如何避免多线程中的死锁问题?

死锁是多线程编程中常见的问题,它指的是两个或多个线程互相等待对方释放资源,导致所有线程都无法继续执行的情况。

避免死锁的一些常见策略:

  • 避免嵌套锁: 尽量避免在一个

    synchronized

    块中获取另一个锁。如果必须获取多个锁,应该按照相同的顺序获取,避免形成循环等待。

  • 使用定时锁: 使用

    tryLock()

    方法尝试获取锁,可以设置超时时间。如果在指定时间内无法获取锁,就放弃获取,避免永久等待。

    import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock;  public class Main {     private static Lock lock1 = new ReentrantLock();     private static Lock lock2 = new ReentrantLock();      public static void main(String[] args) {         Thread thread1 = new Thread(() -> {             try {                 if (lock1.tryLock()) {                     try {                         System.out.println("Thread 1 acquired lock1");                         Thread.sleep(100); // 模拟耗时操作                         if (lock2.tryLock()) {                             try {                                 System.out.println("Thread 1 acquired lock2");                                 // 执行操作                             } finally {                                 lock2.unlock();                             }                         } else {                             System.out.println("Thread 1 failed to acquire lock2, releasing lock1");                             // 释放lock1                         }                     } finally {                         lock1.unlock();                     }                 } else {                     System.out.println("Thread 1 failed to acquire lock1");                 }             } catch (InterruptedException e) {                 e.printStackTrace();             }         });          Thread thread2 = new Thread(() -> {             try {                 if (lock2.tryLock()) {                     try {                         System.out.println("Thread 2 acquired lock2");                         Thread.sleep(100); // 模拟耗时操作                         if (lock1.tryLock()) {                             try {                                 System.out.println("Thread 2 acquired lock1");                                 // 执行操作                             } finally {                                 lock1.unlock();                             }                         } else {                             System.out.println("Thread 2 failed to acquire lock1, releasing lock2");                             // 释放lock2                         }                     } finally {                         lock2.unlock();                     }                 } else {                     System.out.println("Thread 2 failed to acquire lock2");                 }             } catch (InterruptedException e) {                 e.printStackTrace();             }         });          thread1.start();         thread2.start();     } }

    在这个例子中,如果一个线程无法获取所有需要的锁,它会释放已经获取的锁,避免死锁。

  • 使用资源排序: 为所有资源分配一个唯一的编号,线程按照编号的顺序获取资源,避免形成循环等待。

  • 使用死锁检测工具: 一些工具可以帮助检测死锁,例如Java的ThreadMXBean。

如何选择合适的线程池大小?

线程池的大小对程序的性能有很大的影响。 如果线程池太小,可能会导致任务排队等待,降低程序的响应速度。 如果线程池太大,可能会导致过多的线程切换,增加系统的开销。

选择合适的线程池大小需要考虑多个因素,例如CPU核心数、任务的类型(CPU密集型还是IO密集型)、任务的执行时间等。

  • CPU密集型任务: 对于CPU密集型任务,线程池的大小可以设置为CPU核心数+1。 额外的线程可以防止CPU在某个线程阻塞时空闲。

  • IO密集型任务: 对于IO密集型任务,线程池的大小可以设置为CPU核心数的两倍甚至更多。 由于IO操作通常比较耗时,因此需要更多的线程来处理并发的IO请求。

  • 使用

    Runtime.getRuntime().availableProcessors()

    获取CPU核心数: 可以使用

    Runtime.getRuntime().availableProcessors()

    方法来获取当前系统的CPU核心数。

    int cpuCores = Runtime.getRuntime().availableProcessors(); int threadPoolSize = cpuCores * 2; // IO密集型任务
  • 使用

    ExecutorService

    创建线程池: 可以使用

    ExecutorService

    接口和其实现类来创建线程池,例如

    ThreadPoolExecutor

    FixedThreadPool

    import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;  public class Main {     public static void main(String[] args) {         int cpuCores = Runtime.getRuntime().availableProcessors();         int threadPoolSize = cpuCores * 2;         ExecutorService executor = Executors.newFixedThreadPool(threadPoolSize);          for (int i = 0; i < 10; i++) {             int taskNumber = i;             executor.submit(() -> {                 System.out.println("Task " + taskNumber + " running in thread: " + Thread.currentThread().getName());                 try {                     Thread.sleep(1000); // 模拟耗时操作                 } catch (InterruptedException e) {                     e.printStackTrace();                 }             });         }          executor.shutdown(); // 关闭线程池     } }

    在这个例子中,创建了一个固定大小的线程池,线程池的大小是CPU核心数的两倍。

选择合适的线程池大小是一个需要不断尝试和调整的过程。 可以通过监控程序的性能,例如CPU利用率、响应时间等,来调整线程池的大小,以达到最佳的性能。



评论(已关闭)

评论已关闭