开启线程第一种方式:
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秒