方法一
直接使用Thread
//创建线程对象
Thread t = new Thread("可填入线程的名称"){
public void run(){
//要执行的任务
}
};
//启动线程
t.start();
方法二
使用Runnable 配合Thread
Runnable runnable = new Runnable(){
public void run(){
//要执行的任务
}
};
//创建线程对象
Thread t = new Thread(runnable);
//启动线程
t.start();
用lambda版
Runnable runnable () -> {
//要执行的任务
}
};
//创建线程对象
Thread t = new Thread(runnable);
//或者直接在thread中修改
//Thread t = new Thread(()->{//要执行的任务});
//启动线程
t.start();
方法三
FutureTask配合Thread
FutureTask<Integer> task = new FutureTask<>(new Callable<Integer>(){
public Integer call() throws Exception{
//要执行的操作
return 100;
}
});
Thread t = new Thread(task);
t.start();
//获取task的返回值
task.get();