【带返回值的】:
【使用线程池】:
static class MyCall implements Callable<String>{
public String call(){
System.out.println("Hello MyCall");
return "success";
}
}
public static void main(String[] args) throws Exception{
Thread t = new Thread( new FutureTask<String>(new MyCall()));
t.start();
ExecutorService service = Executors.newCachedThreadPool(); //创建线程池。
service.execute(()->{
System.out.println("Hello ThreadPool~~~!!!");
});
//演示使用Callable来拿线程结束时的返回值:
Future<String> future = service.submit(new MyCall()); //Future代表的是一种异步的概念。
String str = future.get();
//get方法是一个阻塞类型的。阻塞类型的意思就是我在这里等着,什么时候装好这个Call拿到值为止。
System.out.println(str);
service.shutdown();
}
【单线程】:
static class MyCall implements Callable<String>{
public String call(){
System.out.println("Hello MyCall");
return "success";
}
}
FutureTask<String> task=new FutureTask<>(new MyCall());
Thread thread = new Thread(task);
thread.start();
System.out.println(task.get());
【FutureTask分析】:
public class FutureTask<V> implements RunnableFuture<V> {
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
}
【如何确定线程数】:
基本上你把它部署上去,进行统计才能确定。——一般来说通过工具测算。(Profiler)如果部署到了远程服务器可以使用Arthas.
根据你CPU计算的能力(核数)来制定线程的数量。一台机器不可能只跑我们自己的程序,肯定还有其他的程序;得看实际中机器的情况。不可能让CPU的利用率达到100% , 出于安全的角度 , 只让其到80即可。
【创建线程的5种方法】:
public class T02_HowToCreateThread {
static class MyThread extends Thread {
@Override
public void run() {
System.out.println("Hello MyThread!");
}
}
static class MyRun implements Runnable {
@Override
public void run() {
System.out.println("Hello MyRun!");
}
}
static class MyCall implements Callable<String>{
public String call(){
System.out.println("Hello MyCall");
return "success";
}
}
//启动线程的5种方式。
public static void main(String[] args) throws Exception{
new MyThread().start();
new Thread(new MyRun()).start();
new Thread(()->{
System.out.println("Hello Lambda!");
}).start();
Thread t = new Thread( new FutureTask<String>(new MyCall()));
t.start();
FutureTask<String> task=new FutureTask<>(new MyCall());
Thread thread = new Thread(task);
thread.start();
System.out.println(task.get());
ExecutorService service = Executors.newCachedThreadPool(); //创建线程池。
service.execute(()->{
System.out.println("Hello ThreadPool~~~!!!");
});
//演示使用Callable来拿线程结束时的返回值:
Future<String> future = service.submit(new MyCall()); //Future代表的是一种异步的概念。
String str = future.get();
//get方法是一个阻塞类型的。阻塞类型的意思就是我在这里等着,什么时候装好这个Call拿到值为止。
System.out.println(str);
service.shutdown();
}
}
//请你告诉我启动线程的三种方式 1:Thread 2: Runnable 3:Executors.newCachedThrad
【本质】:
只有一种——new Thread 出来 , 如果读过线程池/Future 的源码,就会知道最终都是 new 一个 Thread出来。
本质都是——new一个Thread对象 , 并调用它的start方法。