Java创建线程的方式实例分析
作者:暮色微凉
时间:2023-05-02
来源:正软商城
浏览:2
继承Thread,这里使用匿名内部类@Slf4j(topic="c.Test1")publicclassTest1{publicstaticvoidmain(String[]args){//创建线程对象Threadt=newThread(){@Overridepublicvoidrun(){//要执行的任务log.debug("running");}};//设置线程的名字t.setName("t1");//启动线程t.start();log.debug("running");}}/*19:44:31.99
本文目录
继承Thread,这里使用匿名内部类
@Slf4j(topic = "c.Test1")
public class Test1 {
public static void main(String[] args) {
//创建线程对象
Thread t = new Thread(){
@Override
public void run() {
//要执行的任务
log.debug("running");
}
};
//设置线程的名字
t.setName("t1");
//启动线程
t.start();
log.debug("running");
}
}
/*
19:44:31.998 [main] DEBUG c.Test1 - running
19:44:31.998 [t1] DEBUG c.Test1 - running
*/实现Runnable接口,配合Thread类,同样用匿名内部类
把线程和任务分开
Thread表示线程
Runnable代表可运行的任务
@Slf4j(topic = "c.Test2")
public class Test2 {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
//要执行的任务
log.debug("running");
}
};
//创建线程对象
Thread t = new Thread(runnable, "t2");
//启动线程
t.start();
}
}
//19:52:27.646 [t2] DEBUG c.Test2 - running在javajava中,有@FunctionalInterface@FunctionalInterface注解意味着该接口只有一个抽象方法,即可以用lambdalambda表达式的方式简化
@Slf4j(topic = "c.Test2")
public class Test2 {
public static void main(String[] args) {
Runnable runnable = () -> {
//要执行的任务
log.debug("running");
};
//创建线程对象
Thread t = new Thread(runnable, "t2");
//启动线程
t.start();
}
}FutureTask配合Thread
因为FutureTask可以接口一个Callable类型的参数,用来处理有返回值的情况
@Slf4j(topic = "c.Test3")
public class Test3 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//创建任务对象
FutureTask task = new FutureTask<>(() -> {
log.debug("running");
Thread.sleep(1000);
return 100;
});
/*
用lambda化简前
*/
FutureTask task1 = new FutureTask<>(new Callable() {
@Override
public Integer call() throws Exception {
log.debug("running");
Thread.sleep(1000);
return 100;
}
});
//参数1是任务的对象, 参数2是线程的名字
Thread t = new Thread(task, "t3");
t.run();
//主线程堵塞,同步等待task执行完毕的结果
Integer integer = task.get();
log.debug("结果是:{}", integer);
}
}
作者最新文章
PDF怎么按页拆成单独文件?PDF按页拆分后怎么命名
2026-11-03 18:00
长网页转PDF怎么避免断图?网页转PDF怎么设置分页
2026-11-01 09:31
夸克资源库蓝光资源每日更新经典电视剧全集
2026-10-30 11:54
会声会影怎么导入音频 支持格式及步骤
2026-10-29 12:23
WPS表格常用功能实操:从录入到排序筛选的完整流程
2026-10-29 09:57
上一篇:
Java如何实现动物换位游戏
下一篇:
Redis中AOF持久化的示例分析
热门文章
更多
精品专题
更多
Mac软件
更多
火山引擎 网页版
Windows/ macOS/ Linux
火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。
















