【Java并发】使用线程

有三种使用线程的方法:

  • 实现Runnable接口
  • 实现Callable接口
  • 继承Thread类

实现 Runnable 接口

需要实现run() 方法

通过Thread调用start() 方法来启动线程

class MyRunnable implements Runnable {
	@Override
	public void run() {
		System.out.println("run...");
	}
}
public static void main(String[] args) {
	MyRunnable runnable = new MyRunnable();
	Thread thread = new Thread(runnable);
	thread.start();
}

实现 Callable 接口

与Runnable相比,Callable 可以有返回值,返回值通过FutureTask进行封装。

class MyCallable implements Callable<Integer> {
	@Override
	public Integer call() throws Exception {
		System.out.println("call...");
		return 1;
	}
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
	MyCallable callable = new MyCallable();
	FutureTask<Integer> futureTask = new FutureTask<>(callable);
	Thread thread = new Thread(futureTask);
	thread.start();
	System.out.println(futureTask.get());
}

继承 Thread 类

class MyThread extends Thread {
	@Override
	public void run() {
		System.out.println("run...");
	}
}
public static void main(String[] args) {
	MyThread thread = new MyThread();
	thread.start();
}

实现接口 VS 继承 Thread

实现接口会更好一些,因为:

  • Java不支持多重继承,因此继承了Thread类就无法继承其他类,但是可以实现多个接口。
  • 类可能只要求可执行就行,继承整个Thread类开销过大。

参考

CS-Notes

猜你喜欢

转载自blog.csdn.net/qq_21687635/article/details/89948267
今日推荐