開啓線程第一種方式:
public class test {
public static void main(String[] args) {
Thread t1 = new MyThread();
t1.start(); // 開線程
for (int i = 0; i < 100; i++)
System.out.println(Thread.currentThread().getName() + ": B: " + i);
}
}
class MyThread extends Thread {
public void run() {
for (int i = 0; i < 100; i++)
System.out.println(Thread.currentThread().getName() + ": A: " + i);
}
}
開啓線程第二種方式:public class test {
public static void main(String[] args) {
Thread t2 = new Thread(new MyRunnable());
t2.start(); // 開線程
for (int i = 0; i < 100; i++)
System.out.println(Thread.currentThread().getName() + ": B: " + i);
}
}
class MyRunnable implements Runnable {
public void run() {
for (int i = 0; i < 100; i++)
System.out.println(Thread.currentThread().getName() + ": A: " + i);
}
}
使用匿名內部類創建子線程:
new Thread("線程3") {
public void run() {
for (int i = 0; i < 100; i++)
System.out.println(Thread.currentThread().getName() + ": C: " + i);
}
}.start();
new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 100; i++)
System.out.println(Thread.currentThread().getName() + ": D: " + i);
}
}, "線程4").start();
守護線程:
final Thread t1 = new Thread() {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread t2 = new Thread() {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t2.setDaemon(true); // 設置爲守護線程, 不單獨運行
t1.start(); // 5次, 5秒就結束了
t2.start(); // 10次, 需要10秒
// 程序在所有非守護線程執行結束之後才結束
當前線程暫停,等待加入的線程運行結束之後再繼續:
final Thread t1 = new Thread() {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread t2 = new Thread() {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
try {
Thread.sleep(1000);
if(i == 1)
t1.join(); // 當前線程暫停, 等待t1運行結束之後再繼續
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
t1.start(); // 5次, 5秒就結束了
t2.start(); // 10次, 需要10秒