手册目录
Java 教程
Java 方法
Java 类
Java 文件处理
Java 数据结构
Java 案例
Java 参考手册
Java 关键字
Java String 方法
Java Math 方法
Java Output 方法
Java Arrays 类
Java ArrayList 方法
Java LinkedList 方法
Java HashMap 方法
Java Scanner 方法
Java 迭代器接口
Java 错误和异常类型
Java.io 包教程
Java.lang 包教程
Java.math 包教程
java.time 包教程
Java.util 包教程
Java 正则表达式教程
java.util.zip 包教程
前言
在本教程中,您将学习如何使用Java线程,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() 方法来运行线程:
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() 方法来运行线程:
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++;
}
}点击 "运行实例" 按钮查看在线实例
相关视频
科技资讯
24小时阅读榜
1
2
3
4
5
6
7
8
9
10
精品课程
共5课时 | 17.4万人学习
共49课时 | 78.1万人学习
共29课时 | 62.5万人学习
共25课时 | 39.7万人学习
共43课时 | 73.8万人学习