Java实现多线程的三种方法

实现多线程有三种方法

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

Java代码示例

package thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 线程测试
 * @author sunlh
 *
 */
public class ThreadTest {

	public static void main(String[] args) {
		
		// 通过实现Runnable接口实现多线程
		ThreadTest.implRunnable();
		// 通过继承Thread类实现多线程
		ThreadTest.extThread();
		// 通过实现Callable接口来实现多线程
		ThreadTest.callableThread();
	}
	
	/**
	 * 通过实现Runnable接口来实现线程
	 */
	public static void implRunnable() {
		Thread thread = new Thread(new RunnableImpl(), "实现Runnable的线程");
		thread.start();
	}
	
	/**
	 * 通过继承Thread类来实现线程
	 */
	public static void extThread() {
		MyThread thread = new MyThread();
		thread.setName("继承Thread的线程");
		thread.start();
	}
	
	/**
	 * 通过实现Future来实现有返回值的线程
	 */
	public static void callableThread() {
		FutureTask task = new FutureTask<>(new CallableImpl());
		Thread thread = new Thread(task);
		thread.setName("具有返回值的Callable线程");
		thread.start();
		try {
			String result;
			result = task.get();
			System.out.println(result);
		} catch (InterruptedException | ExecutionException e) {
			e.printStackTrace();
		}
	}
}

class CallableImpl implements Callable {

	@Override
	public String call() throws Exception {
		System.out.println(Thread.currentThread().getName());
		return "我是Callable线程的返回值";
	}
	
}

class MyThread extends Thread {

	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName());
	}
}

class RunnableImpl implements Runnable {

	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName());
	}
	
}

你可能感兴趣的:(Java,基础知识)