java.lang.Thread 多線程
public class Thread extends Object implements Runnable
public interface Runnable
Java虛擬機允許應用程序同時執行多個執行線程。
1.創建一個線程有兩種方法:
2.創建多線程的方法:
public class MultiThread implements Runnable {// 繼承Runnable接口類
String name;
int x = 0;
MultiThread(String name) {//構造方法
super();
this.name = name;
}
@Override
public void run() { // 實作父類run方法
while (true) {// 使用while 迴圏 true 不斷循環
System.out.println(this.name + "走了公里數:" + x);
this.x++;
if (this.x == 101) {// // 超過100離開迴圏,離開run方法
break;
}
try {
Thread.sleep(50);// 線程休息50毫秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {// 主方法
MultiThread m1 = new MultiThread("汽車"); // 實例化對象
MultiThread m2 = new MultiThread("機車"); // 實例化對象
MultiThread m3 = new MultiThread("卡車"); // 實例化對象
// 以下啟動多線程,自動分配時間依序執行
new Thread(m1).start();// 實例化Thread線程對象並啟動線程
new Thread(m2).start();// 實例化Thread線程對象並啟動線程
new Thread(m3).start();// 實例化Thread線程對象並啟動線程
}
}