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;
@Slf4j
public class ThreadDemo {
public static void main(String[] args) {
Thread thread1 = new MyThread("t1");
thread1.start();
Runnable target = new MyRunnable();
Thread thread2 = new Thread(target,"t2");
thread2.start();
Thread thread3 = new Thread(() -> {
for (int i = 0; i <= 5; i++){
log.info(Thread.currentThread().getName() + "==>" + i);
}
},"t3");
thread3.start();
Callable<String> callable = new MyCallable();
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);
}
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;
}
}