您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
本篇内容主要讲解“Java创建线程的方式实例分析”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Java创建线程的方式实例分析”吧!
@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
*/把线程和任务分开
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可以接口一个Callable类型的参数,用来处理有返回值的情况
@Slf4j(topic = "c.Test3")
public class Test3 {
public static void main(String[] args) throws ExecutionException, InterruptedException {
//创建任务对象
FutureTask<Integer> task = new FutureTask<>(() -> {
log.debug("running");
Thread.sleep(1000);
return 100;
});
/*
用lambda化简前
*/
FutureTask<Integer> task1 = new FutureTask<>(new Callable<Integer>() {
@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);
}
}到此,相信大家对“Java创建线程的方式实例分析”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。