一、繼承Thread類dom
public class MultiThread { public static void main(String[] args) { System.out.println(Thread.currentThread().getName() + "線程開始運行..."); MultiSayThread t1 = new MultiSayThread("A"); MultiSayThread t2 = new MultiSayThread("B"); t1.start(); t2.start(); System.out.println(Thread.currentThread().getName() + "線程結束運行..."); } } class MultiSayThread extends Thread { public MultiSayThread(String threadName) { super(threadName); } public void run() { System.out.println(getName() + "線程運行開始..."); for (int i = 0; i < 10; i++) { try { System.out.println(i + " " + getName()); sleep((int) Math.random() * 10); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(getName() + "線程運行結束..."); } }
程序運行結果:ide
main線程開始運行... main線程結束運行... A線程運行開始... B線程運行開始... 0 A 0 B 1 B 1 A 2 B 2 A 3 B 3 A 4 B 4 A 5 B 5 A 6 B 6 A 7 B 7 A 8 B 8 A 9 B 9 A B線程運行結束... A線程運行結束...
二、實現Runnablespa
package com.huawei.testthread; public class MultiRunnable { public static void main(String[] args) { System.out.println(Thread.currentThread().getName() + "線程開始運行..."); MultiSaidThread r1 = new MultiSaidThread(); MultiSaidThread r2 = new MultiSaidThread(); Thread t1 = new Thread(r1, "A"); Thread t2 = new Thread(r2, "B"); t1.start(); t2.start(); System.out.println(Thread.currentThread().getName() + "線程結束運行..."); } } class MultiSaidThread implements Runnable { public void run() { System.out.println(Thread.currentThread().getName() + "線程開始運行..."); for (int i = 0; i < 10; i++) { try { System.out.println(i + " " + Thread.currentThread().getName()); Thread.sleep((int) Math.random() * 10); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + "線程結束運行..."); } }
程序運行結果:線程
main線程開始運行... main線程結束運行... A線程開始運行... 0 A 1 A 2 A 3 A 4 A 5 A 6 A 7 A 8 A 9 A A線程結束運行... B線程開始運行... 0 B 1 B 2 B 3 B 4 B 5 B 6 B 7 B 8 B 9 B B線程結束運行...