目录
使用Callable搭配FutureTask(Lambda表达式)
使用Thread匿名内部类创建
指定线程的名称为t1
Thread t1 = new Thread("t1") {
@Override
public void run() {
super.run();
}
};
t1.start();
使用Runnable创建
Runnable runnable = new Runnable() {
@Override
public void run() {
}
};
Thread t1 = new Thread(runnable, "t1");
t1.start();
使用Runnable的lambda表达式
Runnable是一个函数式接口,因此可以通过lambda表达式
@FunctionalInterface
public interface Runnable {
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see java.lang.Thread#run()
*/
public abstract void run();
}
创建线程
Thread t2=new Thread(()->{
while(true) {
System.out.println("lele");
}
},"t1");
t2.start();
使用Callable搭配FutureTask(Lambda表达式)
大家应该理解Lambda表达式了吧
可以点击alt+enter将匿名内部类替换为Lambda,也可以再次点击alt+enter转换回来
Callable搭配FutureTask可以获取结果的返回值,调用FutureTask实例的get()方法同步模式
如果不调用get()方法的话就是异步
Callable是一个函数式接口,因此可以使用Lambda表达式
@FunctionalInterface
public interface Callable<V> {
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
V call() throws Exception;
}
通过FutureTask的构造方法创建对象
public FutureTask(Callable<V> callable) {
if (callable == null)
throw new NullPointerException();
this.callable = callable;
this.state = NEW; // ensure visibility of callable
}
Thread t1 = new Thread(runnable, "t1");
t1.start();
Thread t2=new Thread(()->{
while(true) {
System.out.println("lele");
}
},"t1");
t2.start();
FutureTask task = new FutureTask<Integer>(()->{
System.out.println("乐乐");
return 1;
});
Thread t3 = new Thread(task,"t3");
t3.start();
//等待获取
System.out.println(task.get());