线程的启动

利用Thread类的子类

创建Thread类的子类,创建子类的实例,调用start方法。

PrintThread.java

1
2
3
4
5
6
7
8
9
10
11
12
13
public class PrintThread extends Thread {
private String message;

public PrintThread(String message) {
this.message = message;
}

public void run() {
for (int i = 0; i < 10000; i++) {
System.out.print(message);
}
}
}

Main.java

1
2
3
4
5
6
public class Main {
public static void main(String[] args) {
new PrintThread("Good!").start();
new PrintThread("Nice!").start();
}
}

利用Runnable接口

创建Runnable接口的实现类,将实现类的实例作为参数传给Thread的构造函数,调用start方法。

Printer.java

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Printer implements Runnable {
private String message;

public Printer(String message) {
this.message = message;
}

public void run() {
for (int i = 0; i < 10000; i++) {
System.out.print(message);
}
}
}

Main.java

1
2
3
4
5
6
public class Main {
public static void main(String[] args) {
new Thread(new Printer("Good!")).start();
new Thread(new Printer("Nice!")).start();
}
}

补充

java.util.concurrent包中包含一个将线程创建抽象化的ThreadFactory接口。利用该接口,可以将以Runnable作为传入参数并通过new创建Thread实例的处理隐藏在ThreadFactory内部。

Main.java

1
2
3
4
5
6
7
8
9
10
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

public class Main {
public static void main(String[] args) {
ThreadFactory factory = Executors.defaultThreadFactory();
factory.newThread(new Printer("Good!")).start();
factory.newThread(new Printer("Nice!")).start();
}
}