java - 创建线程的几种方法

public class CreateThread {
	public static void main(String[] args) throws ExecutionException, InterruptedException {
    	//1. 继承Thread类,重写run方法
    	NewThread newThread = new NewThread("继承Thread类,重写run方法");
    	newThread.start();
    	//2. 实现Runnable接口,重写run方法
    	new Thread(() -> {
        	System.out.println("实现Runable接口,重写run方法开始执行");
    	}).start();
    	//3. 实现Callable接口,重写call方法,使用FutureTask接收,并获取执行结果
    	FutureTask<String> callTask = new FutureTask<>(() -> {
        	System.out.println("实现Callable接口,重写call方法开始执行");
        	return "call方法执行成功";
    	});
    	new Thread(callTask).start();
    	System.out.println("call方法执行结果:" + callTask.get());

    	//4. 使用线程池执行实现Runnable接口的线程
    	ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 2, 1000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(2));
    	threadPoolExecutor.execute(() -> {
        	System.out.println("实现Runable接口,重写run方法,线程池开始执行");
    	});
    	//5. 使用线程池执行实现Callable接口的线程
    	System.out.println("call方法执行结果:" + threadPoolExecutor.submit(() -> {
        	System.out.println("实现Callable接口,重写call方法,线程池开始执行");
        	return "call方法执行成功";
    	}).get());
	}

	static class NewThread extends Thread{

    		public NewThread() {
    		}

    		@Override
    		public void run() {
        		System.out.println(Thread.currentThread().getName() + "开始执行");
    		}

	}
}

执行结果

image

posted @ 2025-02-08 09:40  卡利的亲爹  阅读(14)  评论(0)    收藏  举报