❤️💕💕java的学习指南,从入门到大师篇章。Myblog:http://nsddd.top
[TOC]
- 线程允许程序通过同时执行多项操作来更有效地运行。
- 线程可以用来在后台执行复杂的任务而不中断主程序。
创建线程有两种方法。
它可以通过扩展Thread
类并覆盖其run()
方法来创建:
public class Main extends Thread {
public void run() {
System.out.println("This code is running in a thread");
}
}
创建线程的另一种方法是实现Runnable
接口:
public class Main implements Runnable {
public void run() {
System.out.println("This code is running in a thread");
}
}
如果该类扩展了Thread
该类,则可以通过创建该类的实例并调用其start()
方法来运行线程:
public class Main extends Thread {
public static void main(String[] args) {
Main thread = new Main();
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");
}
}
//This code is outside of the thread
//This code is running in a thread
如果类实现了Runnable
接口,则可以通过将类的实例传递给Thread
对象的构造函数然后调用线程的 start()
方法来运行线程:
public class Main implements Runnable {
public static void main(String[] args) {
Main obj = new Main();
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");
}
}
“扩展”和“实现”线程之间的区别
主要区别在于,当一个类扩展 Thread 类时,您不能扩展任何其他类,但是通过实现 Runnable 接口,也可以从另一个类扩展,例如: class
MyClass extends OtherClass implements Runnable
。
因为线程与程序的其他部分同时运行,所以无法知道代码将以何种顺序运行。当线程和主程序读取和写入相同的变量时,其值是不可预测的。由此产生的问题称为并发问题。
变量数量的值不可预测的代码示例:
public class Main extends Thread {
public static void main(String[] args) {
Main thread = new Main();
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");
}
}
编译:(下面的顺序是没用办法预测的❌)
This code is outside of the thread
This code is outside of the thread
This code is running in a thread
**为了避免并发问题,最好在线程之间共享尽可能少的属性。**如果需要共享属性,一种可能的解决方案是在使用isAlive()
线程可以更改的任何属性之前,使用线程的方法检查线程是否已完成运行。
用于isAlive()
防止并发问题:
public class Main extends Thread {
public static int amount = 0;
public static void main(String[] args) {
Main thread = new Main();
thread.start();
// Wait for the thread to finish 等待线程完成wait()
while(thread.isAlive()) {
System.out.println("Waiting...");
}
// Update amount and print its value 更新数量并打印其值
System.out.println("Main: " + amount);
amount++;
System.out.println("Main: " + amount);
}
public void run() {
amount++;
}
}
编译:
Waiting...
Main: 1
Main: 2