Java创建线程的几种方式

package com.bt.springboot.demo;

import lombok.extern.slf4j.Slf4j;

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

/**
 * @author
 * @Date 2022/10/18 20:54
 */
@Slf4j
public class ThreadDemo {

	public static void main(String[] args) {

		// 创建方式1
		Thread thread1 = new MyThread("t1");
		thread1.start();

		// 创建方式2
		// 创建一个线程任务对象
		Runnable target = new MyRunnable();
		// 把线程任务对象包装成线程对象,且可以指定线程名称
		Thread thread2 = new Thread(target,"t2");
		thread2.start();

		// 方式2匿名内部类写法
		Thread thread3 = new Thread(() -> {
			for (int i = 0; i <= 5; i++){
				log.info(Thread.currentThread().getName() + "==>" + i);
			}
		},"t3");
		thread3.start();

		// 创建方式3
		// 创建callable线程任务对象
		Callable<String> callable = new MyCallable();
		// 把Callable任务对象包装成未来任务对象
		// 未来任务对象其实就是runnable对象,这样就可以被包装成线程对象
		// 未来任务对象可以在线程执行完后得到线程结果
		FutureTask<String> futureTask = new FutureTask<>(callable);
		Thread thread4 = new Thread(futureTask,"t4");
		thread4.start();


		// 线程的执行方法
		for (int i = 0; i <= 5; i++) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				Thread.currentThread().interrupt();
			}
			log.info("主线程输出:" + i);
		}

		// 获取call方法执行的结果
		try {
			String rs = futureTask.get();
			log.info("call结果:{}",rs);
		} catch (InterruptedException | ExecutionException e) {
			Thread.currentThread().interrupt();
		}
	}

}

@Slf4j
class MyThread extends Thread {

	public MyThread(String name) {
		super(name);
	}

	@Override
	public void run() {
		// 线程的执行方法
		for (int i = 0; i <= 5; i++) {
			log.info(Thread.currentThread().getName() + "线程输出:" + i);
		}
	}
}
@Slf4j
class MyRunnable implements Runnable {

	@Override
	public void run() {
		for (int i = 0; i <= 5; i++){
			log.info(Thread.currentThread().getName() + "==>" + i);
		}
	}
}

@Slf4j
class MyCallable implements Callable<String> {

	@Override
	public String call() {

		int sum = 0;
		for (int i = 0; i <= 5; i++){
			log.info(Thread.currentThread().getName() + "==>" + i);
			sum += i;
		}

		return Thread.currentThread().getName() + "执行结果" + sum;
	}
}

你可能感兴趣的:(JavaEE,java)