public class Test {
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}
class MyThread extends Thread{
@Override
public void run() {
super.run();
System.out.println("新的线程启动了");
}
}
2,实现Runnable接口
public class Test {
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}
class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println("新的线程启动了");
}
}
3,实现Callable接口
public class Test {
public static void main(String[] args) throws Exception {
FutureTask<String> futureTask = new FutureTask<>(new MyCallable());
Thread thread = new Thread(futureTask);
thread.start();
System.out.println("Callable线程返回值为:" + futureTask.get());
}
}
class MyCallable implements Callable<String>{
@Override
public String call() throws Exception {
System.out.println("新的线程启动了");
return "success";
}
}
Future AP介绍(用于FutureTask控制它关联的Callable任务):
V get():返回Callable任务里call()方法的返回值,该方法导致程序阻塞,必须等到子线程call()结束后才会得到返回值;
V get(long timeout,TimeUnit unit):返回Callable任务里的call()方法的返回值,该方法最多让程序阻塞timeout和unit指定的时间,如果在指定的时间未返回,则抛出异常;