位置:首页 > PHP > Java多线程开发指南:从创建到同步安全的完整解析

Java多线程开发指南:从创建到同步安全的完整解析

时间:2026-11-12  |  作者:风起客  |  阅读:0

对于尚未深入研究Java并发机制的开发者而言,掌握多线程原理是提升应用性能的关键。本指南旨在通过系统化的梳理,帮助你透彻理解Java中线程的运作逻辑、标准用法以及常见的安全陷阱,从而构建更稳健的多线程应用。

资源免费获取入口夸克直达:☜☜☜☜☜点击进入

一、线程的创建方式

在Java生态中,启动新线程主要依赖两种途径:直接继承Thread类或实现Runnable接口。无论选择哪种路径,底层都需要实例化一个Thread对象来承载任务。理解Thread类的构造函数及其参数含义,是正确初始化线程的基础。以下是Thread类常用的构造方法签名:

  1. public Thread( );
  2. public Thread(Runnable target);
  3. public Thread(String name);
  4. public Thread(Runnable target, String name);
  5. public Thread(ThreadGroup group, Runnable target);
  6. public Thread(ThreadGroup group, String name);
  7. public Thread(ThreadGroup group, Runnable target, String name);
  8. public Thread(ThreadGroup group, Runnable target, String name, long stackSize);

方式一:通过继承Thread类并重写run方法

public class ThreadDemo1 {
  public static void main(String[] args){
   Demo d = new Demo();
   d.start();
   for(int i=0;i<60;i++){
    System.out.println(Thread.currentThread().getName()+i);
   }

  }
 }
 class Demo extends Thread{
  public void run(){
   for(int i=0;i<60;i++){
    System.out.println(Thread.currentThread().getName()+i);
   }
  }
 }

方式二:通过实现Runnable接口

public class ThreadDemo2 {
 public static void main(String[] args){
  Demo2 d =new Demo2();
  Thread t = new Thread(d);
  t.start();
  for(int x=0;x<60;x++){
   System.out.println(Thread.currentThread().getName()+x);
  }
 }
}
class Demo2 implements Runnable{
 public void run(){
  for(int x=0;x<60;x++){
   System.out.println(Thread.currentThread().getName()+x);
  }
 }
}

二、线程的生命周期与状态控制

如同人类经历出生、成长、休息和死亡,Java线程也拥有明确的状态流转过程,主要包括新建(New)、就绪(Runnable)、运行(Running)、阻塞/挂起(Blocked/Suspended)和终止(Terminated)。Thread类提供了相应的方法来控制这些状态的切换,开发者需熟悉这些API以避免误用。

// 启动线程的核心方法
publicvoid start( );
publicvoid run( );
// 线程暂停与恢复(注:旧版API,现代开发中已不推荐)
publicvoid resume( ); // 不建议使用
publicvoid suspend( ); // 不建议使用
publicstaticvoid sleep(long millis);
publicstaticvoid sleep(long millis, int nanos);
// 线程中断与终止相关方法
publicvoid stop( ); // 极不安全,不建议使用
publicvoid interrupt( );
// 查询线程存活及中断状态
publicboolean isAlive( );
publicboolean isInterrupted( );
publicstaticboolean interrupted( );
// 线程Join操作,用于等待子线程结束
publicvoid join( ) throws InterruptedException;

线程对象创建后并不会立即执行任务代码,而是处于“新建”状态。在此阶段,你可以配置线程的各种属性,例如设置优先级(setPriority)、指定线程名称(setName)或将其设为守护线程(setDaemon)。只有调用start()方法后,线程才会进入可运行状态,由JVM调度执行。

当线程被调度执行run()方法内的代码时,它处于“运行”状态。此时可以通过isAlive()方法检测线程是否仍在活动。如果isAlive()返回true,说明线程正在运行或已启动但未结束;若返回false,则可能处于未启动或已终止状态。以下代码展示了如何观察线程从创建到运行的状态变化及isAlive的返回值。

一旦线程开始执行run方法,它将持续运行直至方法体执行完毕。但在执行过程中,可能需要临时暂停线程。早期API提供了suspend和resume方法,但由于其容易导致死锁等不可控后果,目前已标记为废弃。现代开发中,通常使用sleep()让线程暂时休眠,或使用interrupt()进行中断。sleep结束后,线程进入“就绪”队列,等待CPU调度,而非直接运行。

在使用sleep()方法时,有两个关键细节需要特别注意:

1. sleep方法支持毫秒和纳秒两个精度级别。然而,大多数操作系统和JVM实现的计时器精度无法达到纳秒级。因此,即使传入纳秒参数,JVM也会将其转换为最接近的毫秒值进行处理,实际休眠时间可能与预期存在微小偏差。

2. sleep方法声明抛出了InterruptedException异常。由于run()方法本身不能声明抛出受检异常,因此在run内部调用sleep时,必须使用try-catch块包裹,或者在外部捕获。如果在睡眠期间其他线程调用了该线程的interrupt()方法,sleep会抛出此异常并清除中断状态。

publicstaticvoid sleep(long millis) throws InterruptedException
publicstaticvoid sleep(long millis, int nanos) throws InterruptedException

终止线程主要有三种策略,其中前两种为推荐做法,第三种需谨慎使用。

1. 使用标志位正常退出:这是最安全的方式。在run方法中使用循环处理任务,并通过一个volatile boolean变量作为退出标志。当条件满足时,将标志置为false,循环自然结束,线程平滑退出。

2. 使用stop()方法强行终止:此方法已被官方弃用。因为它会立即释放所有监视器锁,可能导致数据不一致、死锁或其他难以预测的系统错误,严禁在现代并发代码中使用。

3. 使用interrupt()方法中断:通过向线程发送中断信号,配合检查中断状态来实现终止。这是一种协作式的终止方式,允许线程在合适的时间点清理资源并退出。

1. 使用退出标志终止线程的最佳实践

通常情况下,run方法执行完毕线程即自动终止。但对于服务端监听、后台轮询等长期运行的任务,往往需要置于while(true)循环中。为了防止无限循环导致资源耗尽,应引入一个布尔类型的控制标志。通过外部修改该标志的值,可以优雅地打破循环,使线程在完成当前逻辑后正常退出。

join()方法的作用是让主线程等待子线程执行完毕后再继续。默认情况下,调用start()后主线程不会等待,直接执行后续代码。如果后续逻辑依赖于子线程的计算结果,必须使用join()。该方法会使调用它的线程阻塞,直到目标线程终止。这保证了线程执行的顺序性和数据的完整性。

三、多线程环境下的安全问题

并发问题的根源在于:当多个线程同时访问和修改同一个共享资源(如变量、对象)时,如果缺乏同步机制,一个线程的操作可能被另一个线程打断,导致数据读写混乱、计算错误或状态不一致。

解决思路:确保对共享数据的操作具有原子性。即在某个线程执行完对共享资源的所有操作之前,其他线程不得介入。这通常通过“互斥锁”机制实现。

方案一:使用同步代码块(Synchronized Block)

public class ThreadDemo3 {
 public static void main(String[] args){
  Ticket t =new Ticket();
  Thread t1 = new Thread(t,"窗口一");
  Thread t2 = new Thread(t,"窗口二");
  Thread t3 = new Thread(t,"窗口三");
  Thread t4 = new Thread(t,"窗口四");
  t1.start();
  t2.start();
  t3.start();
  t4.start();
 }
}
class Ticket implements Runnable{
 private int ticket =400;
 public void run(){
  while(true){
   synchronized (new Object()) {
    try {
     Thread.sleep(1);
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
    if(ticket<=0)
     break;
    System.out.println(Thread.currentThread().getName()+"---卖出"+ticket--);
   }
  }
 }
}

方案二:使用同步方法(Synchronized Method)

public class ThreadDemo3 {
 public static void main(String[] args){
  Ticket t =new Ticket();
  Thread t1 = new Thread(t,"窗口一");
  Thread t2 = new Thread(t,"窗口二");
  Thread t3 = new Thread(t,"窗口三");
  Thread t4 = new Thread(t,"窗口四");
  t1.start();
  t2.start();
  t3.start();
  t4.start();
 }
}
class Ticket implements Runnable{
 private int ticket = 4000;
 public synchronized void saleTicket(){
  if(ticket>0)
   System.out.println(Thread.currentThread().getName()+"卖出了"+ticket--);

 }
 public void run(){
  while(true){
   saleTicket();
  }
 }
}

关于锁对象的辨析:普通同步方法的锁对象是当前实例(this),而静态同步方法(static synchronized)的锁对象是该类的Class对象。理解锁的范围有助于避免不必要的性能瓶颈或死锁。

四、线程间的通信与协作

public class ThreadDemo3 {
 public static void main(String[] args){
  class Person{
   public String name;
   private String gender;
   public void set(String name,String gender){
    this.name =name;
    this.gender =gender;
   }
   public void get(){
    System.out.println(this.name+"...."+this.gender);
   }
  }
  final Person p =new Person();
  new Thread(new Runnable(){
   public void run(){
    int x=0;
    while(true){
     if(x==0){
      p.set("张三", "男");
     }else{
      p.set("lili", "nv");
     }
     x=(x+1)%2;
    }
   }
  }).start();
  new Thread(new Runnable(){
   public void run(){
    while(true){
     p.get();
    }
   }
  }).start();
 }
}
/*
张三....男
张三....男
lili....nv
lili....男
张三....nv
lili....男
*/

上述代码存在竞争条件,输出结果不可预测。为解决此问题,需对读写操作加锁。

public class ThreadDemo3 {
  public static void main(String[] args){
   class Person{
    public String name;
    private String gender;
    public void set(String name,String gender){
     this.name =name;
     this.gender =gender;
    }
    public void get(){
     System.out.println(this.name+"...."+this.gender);
    }
   }
   final Person p =new Person();
   new Thread(new Runnable(){
    public void run(){
     int x=0;
     while(true){
      synchronized (p) {
       if(x==0){
        p.set("张三", "男");
       }else{
        p.set("lili", "nv");
       }
       x=(x+1)%2; 
      }

     }
    }
   }).start();
   new Thread(new Runnable(){
    public void run(){
     while(true){
      synchronized (p) {
       p.get();
      }
     }
    }
   }).start();
  }

 }
 /*
 lili....nv
 lili....nv
 lili....nv
 lili....nv
 lili....nv
 lili....nv
 张三....男
 张三....男
 张三....男
 张三....男
 */

进阶:等待与唤醒机制(Wait/Notify)

/*
 *线程等待唤醒机制
 *等待和唤醒必须是同一把锁 
 */
public class ThreadDemo3 {
 private static boolean flags =false;
 public static void main(String[] args){
  class Person{
   public String name;
   private String gender;
   public void set(String name,String gender){
    this.name =name;
    this.gender =gender;
   }
   public void get(){
    System.out.println(this.name+"...."+this.gender);
   }
  }
  final Person p =new Person();
  new Thread(new Runnable(){
   public void run(){
    int x=0;
    while(true){
     synchronized (p) {
      if(flags)
       try {
        p.wait();
       } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       };
      if(x==0){
       p.set("张三", "男");
      }else{
       p.set("lili", "nv");
      }
      x=(x+1)%2;
      flags =true;
      p.notifyAll();
     }
    }
   }
  }).start();
  new Thread(new Runnable(){
   public void run(){
    while(true){
     synchronized (p) {
      if(!flags)
       try {
        p.wait();
       } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
       };
      p.get();
      flags =false;
      p.notifyAll();
      }
    }
   }
  }).start();
 }
}

经典场景:生产者-消费者模型(基础版)

public class ThreadDemo4 {
 private static boolean flags =false;
 public static void main(String[] args){
  class Goods{
   private String name;
   private int num;
   public synchronized void produce(String name){
    if(flags)
     try {
      wait();
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    this.name =name+"编号:"+num++;
    System.out.println("生产了...."+this.name);
    flags =true;
    notifyAll();
   }
   public synchronized void consume(){
    if(!flags)
     try {
      wait();
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    System.out.println("消费了******"+name);
    flags =false;
    notifyAll();
   }

  }
  final Goods g =new Goods();
  new Thread(new Runnable(){
   public void run(){
    while(true){
     g.produce("商品");
    }
   }
  }).start();
  new Thread(new Runnable(){
   public void run(){
    while(true){
     g.consume();
    }
   }
  }).start();
 }
}

经典场景:生产者-消费者模型(多生产者/消费者版)

public class ThreadDemo4 {
 private static boolean flags =false;
 public static void main(String[] args){
  class Goods{
   private String name;
   private int num;
   public synchronized void produce(String name){
    while(flags)
     try {
      wait();
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    this.name =name+"编号:"+num++;
    System.out.println(Thread.currentThread().getName()+"生产了...."+this.name);
    flags =true;
    notifyAll();
   }
   public synchronized void consume(){
    while(!flags)
     try {
      wait();
     } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    System.out.println(Thread.currentThread().getName()+"消费了******"+name);
    flags =false;
    notifyAll();
   }

  }
  final Goods g =new Goods();
  new Thread(new Runnable(){
   public void run(){
    while(true){
     g.produce("商品");
    }
   }
  },"生产者一号").start();
  new Thread(new Runnable(){
   public void run(){
    while(true){
     g.produce("商品");
    }
   }
  },"生产者二号").start();
  new Thread(new Runnable(){
   public void run(){
    while(true){
     g.consume();
    }
   }
  },"消费者一号").start();
  new Thread(new Runnable(){
   public void run(){
    while(true){
     g.consume();
    }
   }
  },"消费者二号").start();
 }
}
/*
消费者二号消费了******商品编号:48049
生产者一号生产了....商品编号:48050
消费者一号消费了******商品编号:48050
生产者一号生产了....商品编号:48051
消费者二号消费了******商品编号:48051
生产者二号生产了....商品编号:48052
消费者二号消费了******商品编号:48052
生产者一号生产了....商品编号:48053
消费者一号消费了******商品编号:48053
生产者一号生产了....商品编号:48054
消费者二号消费了******商品编号:48054
生产者二号生产了....商品编号:48055
消费者二号消费了******商品编号:48055
*/

总结与注意事项:以上内容涵盖了Java多线程开发的核心知识点。在实际项目中,建议优先使用java.util.concurrent包下的高级并发工具类(如ExecutorService、CountDownLatch等),它们封装了底层的锁和线程管理逻辑,能显著降低开发难度并提高代码安全性。本文内容仅供技术学习与参考,不构成任何投资建议或商业指导。加密货币及相关市场波动剧烈,投资者应独立判断,谨慎决策。

免责声明:文中图文均来自网络,如有侵权请联系删除,心愿游戏发布此文仅为传递信息,不代表心愿游戏认同其观点或证实其描述。

相关文章

更多

精选合集

更多

大家都在玩

热门话题

大家都在看

更多