import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class ThreadTest {
//方法一:继承Thread
@Test
public void test() {
for(int i=0;i<10;i++) {
final int num = i;
new Thread() {
@Override
public void run() {
System.out.println("线程"+num+"执行");
}
}.start();
}
}
//方法二:实现Runnable,对象作为Thread构造方法参数
@Test
public void test2() {
for(int i=0;i<10;i++) {
final int num = i;
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("线程"+num+"执行");
}
}).start();
}
}
//方法三:使用Callable和Future(可以获取子线程返回值,call方法可抛异常)
class MyCallable implements Callable{
@Override
public Object call() throws Exception {
String name = Thread.currentThread().getName();
return name;
}
}
@Test
public void test3() {
MyCallable myCallable = new MyCallable();
for(int i=0;i<10;i++) {
FutureTask futureTask = new FutureTask(myCallable);
new Thread(futureTask, "子线程"+i).start();
try {
System.out.println("子线程返回值" + futureTask.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
}