简图
Thread常见的3种创建方法- Runnable方式:
Runnable方式没有返回值。
/**
* @author jtl
* @date 2019/10/11 17:03
* Thread常见的3种创建方法:Runnable
*/
public class ThreadDemo {
public static void main(String[] args) {
//Runnable
Thread threadA=new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Thread is created with runnable");
}
},"ThreadA");
threadA.start();
}
}
- FutureTask方式:
FutureTask:有返回值。在执行futureTask.get()方法时。会阻塞当前线程,直到futureTask所在子线程执行完,才会唤醒当前线程。
/**
* @author jtl
* @date 2019/10/11 17:03
* Thread常见的3种创建方法: FutureTask
*/
public class ThreadDemo {
public static void main(String[] args) {
//FutureTask callable
Callable<String> callable=new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(1000);
return "Thread is created with callable";
}
};
FutureTask<String> futureTask=new FutureTask<>(callable);
Thread threadB=new Thread(futureTask,"ThreadB");
threadB.start();
try {
long tt=System.currentTimeMillis();
String msg=futureTask.get();
// 在执行futureTask.get() 会阻塞当先线程,直到子线程执行完毕,才会唤醒主线程
// 所以时间耗费为1000+ms
System.out.println(msg+"---" +(System.currentTimeMillis()-tt));
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
- Thread子类的方式:
/**
* @author jtl
* @date 2019/10/11 17:03
* Thread常见的3种创建方法:Thread子类
*/
public class ThreadDemo {
public static void main(String[] args) {
ThreadC threadC=new ThreadC();
threadC.setName("ThreadC");
threadC.start();
}
private static class ThreadC extends Thread{
@Override
public void run() {
super.run();
System.out.println("ThreadC name is: "+getName());
}
}
}
网友评论