您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

Java创建线程的方式实例分析

2024/5/10 18:53:31发布21次查看
继承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 - running19: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<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创建线程的方式实例分析的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product