创建多线程并启动
public class TestThread {public static void main(String[] args) throws InterruptedException {Thread t1 = new MyThread1();MyThread2 mt2 = new MyThread2();Thread t2 = new Thread(mt2);t1.start();t2.start();}
}//繼承自 `Thread` 類創建線程類
class MyThread1 extends Thread {private int i = 0;//無參構造方法,調用父類構造方法設置線程名稱public MyThread1() {super("我的線程1");}//通過循環判斷,輸出10次,每次間隔0.5秒public void run() {try {while (i < 10) {System.out.println(this.getName() + "運行第" + (i + 1) + "次");i++;//在指定的毫秒數內讓當前正在執行的線程休眠(暫停執行)sleep(500);}} catch (Exception e) {e.printStackTrace();}}
}//實現Runnable接口創建線程類
class MyThread2 implements Runnable {String name = "我的線程2";public void run() {System.out.println(this.name);}
}
總結
- 上一篇: 使用 Servlet 读取表单数据
- 下一篇: 定义线程的两种方式