Java 创建线程的多种方式
1. 继承 Thread 类(不推荐)
继承 Thread 类的方法:
public class Type1 {
public static void main(String[] args) throws InterruptedException {
MyThread thread = new MyThread();
MyThread thread2 = new MyThread();
thread.start();
thread2.start();
System.out.println(thread);
System.out.println(thread2);
}
}
/**
* 1. 继承 Thread 类
*/
class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.print(i + " ");
}
}
}
这种方法有个缺点,因为 Java 只能单继承,所以如果如果只要继承了 Thread 类,就不能再继承其他类了,失去了可扩展性。
Java 可以实现继承和实现,若继承了 Thread 就无法继承其他类了:
class Test extends Object implements TestIn {}
2. 实现 Runnable 接口
实现 Runnable 接口方法:
public class Type2 {
public static void main(String[] args) {
Thread thread = new Thread(new MyThread(), "task1");
Thread thread2 = new Thread(new MyThread(), "task2");
thread.start();
thread2.start();
System.out.println(thread);
System.out.println(thread2);
}
}
/**
* 2. 实现 Runnable 接口
*/
class MyThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.print(i + " ");
}
}
}
实现 Runnable 接口,这样解决了继承 Thread 所带来的缺点。用实现 Runnable 的类去初始化 Thread 即可。
3. 实现 Callable 接口
Runnable
接口无法实现的功能:当线程终止时(即 run()
完成时),我们无法使线程反回结果。为了支持此功能,Java 中提供了 Callable
接口。
- 实现 Callable 接口的
call()
方法,可以抛出异常,并且具有返回值。
Runnable
接口有个实现类 FutureTask
,FutureTask
构造可以传递实现 Callable
接口的对象。
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class Type3 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<Integer> task1 = new FutureTask<>(new MyThread());
FutureTask<Integer> task2 = new FutureTask<>(()->{
int s = 0;
for (int i = 1; i <= 100; i++) {
s += i;
}
System.out.println(Thread.currentThread().getName() + " completed!");
Thread.sleep(1000);
return s;
});
Thread thread = new Thread(task1, "t1");
Thread thread2 = new Thread(task2, "t2");
thread.start();
thread2.start();
while (!task1.isDone()) {
System.out.println("task1 waiting....");
}
System.out.println(task1.get());
System.out.println(task2.get());
System.out.println(Thread.currentThread().getName() + " completed!");
}
}
class MyThread implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int s = 0;
for (int i = 1; i < 200; i++) {
s += i;
}
System.out.println(Thread.currentThread().getName() + " completed!");
return s;
}
}
附录
可以设置优先级 [1-10]
,默认为 5
,10 优先级最高。
计算代码运行时间:
long start = System.currentTimeMillis();
long end = System.currentTimeMillis();
System.out.println("共耗时"+ (end - start) +"毫秒");