Java 创建线程的两种方式
线程是在一个进程里,一个并发执行的顺序的流程。
例如,考虑一个文本编辑器,它在输入特定长度的文本后执行自动保存操作。
现在有两个任务,首先显示输入到编辑器中的文本,然后执行自动保存。
因为这两个任务应该并行执行,所以它们在不同的线程中执行。如果两个操作都在同一个线程上执行,那么当线程忙于保存时,它就不能执行输入过程,并且会显示一个延迟,直到保存操作完成。
创建线程有两种方法。
继承Thread类
每个线程都是线程的一个实例。因此,可以通过扩展thread类来创建一个新线程。扩展Thread的类应该运行其中定义的方法。Run方法包含要在线程中执行的任务。通过调用start方法启动新线程。
参考代码如下:
public class NewThread extends Thread {
public static void main(String[] args) {
System.out.println("This is thread:\"" + Thread.currentThread().getName() + "\"");
NewThread thread = new NewThread ();
//start new thread
thread.start();
}
public void run() {
System.out.println("This is thread:\"" + Thread.currentThread().getName() + "\"");
}
}
输出:
This is thread: “main”
This is thread: “Thread-0”
实现Runnable接口
创建新线程的另一种方法Runnable接口。Runnable是java中的一个接口。当您实现Runnable时,您必须在类中提供run方法的定义,而这个run方法就是要在线程中执行的任务。
为了启动线程,我们需要创建thread类的对象(或扩展thread的类),并将该类的对象(实现Runnable)传递给thread类构造函数,如下图所示:
public class NewTask implements Runnable {
public static void main(String[] args) {
System.out.println("This is thread:\"" + Thread.currentThread().getName() + "\"");
Thread ob = new Thread(new NewTask());
ob.start();
}
public void run() {
System.out.println("This is thread:\"" + Thread.currentThread().getName() + "\"");
}
}
输出:
This is thread: “main”
This is thread: “Thread-0”
注意
- 线程表示要与其他任务一起执行的任务。
- 无论是继承Thread类还是实现Runnable接口,它需要定义一个run()方法。
- 方法签名为public void run() { }
- run方法的访问修饰符应该是public的。原因很简单,我们正在实现一个接口的运行方法,它是隐式公共的,我们不能在实现/覆盖时降低方法的可见性。
- run()方法是Runnable接口中定义。
- start()方法是Thread类定义的而不是Runnable接口中定义。
- 线程实例不能直接调用start()方法
public class MyClass implements Runnable {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.start(); //<strong>compiler error here</strong>
}
}
The method start() is undefined for the type MyClass