Java 线程

创建于 2024-12-02 / 25
字体: [默认] [大] [更大]

Java 线程

线程允许程序通过同时执行多项操作来更有效地运行。

线程可以用来在后台执行复杂的任务而不中断主程序。


创建线程

创建线程有两种方法。

它可以通过扩展 Thread 类并覆盖其 run() 方法来创建:

扩展语法

public class MyClass extends Thread {
  public void run() {
    System.out.println("This code is running in a thread");
  }
}

另一种创建线程的方法是实现 Runnable 接口:

实现语法

public class MyClass implements Runnable {
  public void run() {
    System.out.println("This code is running in a thread");
  }
}

运行线程

如果该类扩展了 Thread 类,则可以通过创建该类的实例并调用其 start() 方法来运行线程:

Extend 实例

public class MyClass extends Thread {
  public static void main(String[] args) {
    MyClass thread = new MyClass();
    thread.start();
    System.out.println("This code is outside of the thread");
  }
  public void run() {
    System.out.println("This code is running in a thread");
  }
}

运行实例 »

如果类实现了 Runnable 接口,则可以通过将类的实例传递给 Thread 对象的构造函数,然后调用线程的 start() 方法来运行线程:

Implement 实例

public class MyClass implements Runnable {
  public static void main(String[] args) {
    MyClass obj = new MyClass();
    Thread thread = new Thread(obj);
    thread.start();
    System.out.println("This code is outside of the thread");
  }
  public void run() {
    System.out.println("This code is running in a thread");
  }
}

运行实例 »

"extending" 和 "implementing" 线程之间的区别

主要区别在于,当一个类扩展 Thread 类时,您不能扩展任何其他类,但通过实现 Runnable 接口,也可以从另一个类扩展,例如: class MyClass extends OtherClass implements Runnable.


并发问题

因为线程与程序的其他部分同时运行,所以无法知道代码将以何种顺序运行。当线程和主程序读取和写入相同的变量时,其值是不可预测的。由此产生的问题称为并发问题。

实例

变量数量的值不可预测的代码示例:

public class MyClass extends Thread {
  public static int amount = 0;

  public static void main(String[] args) {
    MyClass thread = new MyClass();
    thread.start();
    System.out.println(amount);
    amount++;
    System.out.println(amount);
  }

  public void run() {
    amount++;
  }
}

运行实例 »

为了避免并发问题,最好在线程之间共享尽可能少的属性。如果需要共享属性,一种可能的解决方案是在使用线程可以更改的任何属性之前,使用线程的 isAlive() 方法检查线程是否已完成运行。

实例

使用 isAlive() 来防止并发问题:

public class MyClass extends Thread {
  public static int amount = 0;

  public static void main(String[] args) {
    MyClass thread = new MyClass();
    thread.start();
    // 等待线程完成
    while(thread.isAlive()) {
    System.out.println("Waiting...");
  }
  // 更新 amount 并打印其值
  System.out.println("Main: " + amount);
  amount++;
  System.out.println("Main: " + amount);
  }
  public void run() {
    amount++;
  }
}

运行实例 »



0 人点赞过