您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
这期内容当中小编将会给大家带来有关Java如何在不同线程中实现运行,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
具体如下:
start()方法开始为一个线程分配CPU时间,这导致对run()方法的调用。
代码1
package Threads; /** * Created by Frank */ public class ThreadsDemo1 extends Thread { private String msg; private int count; public ThreadsDemo1(final String msg, int n) { this.msg = msg; count = n; setName(msg + " runner Thread"); } public void run() { while (count-- > 0) { System.out.println(msg); try { Thread.sleep(100); } catch (InterruptedException e) { return; } } System.out.println(msg + " all done."); } public static void main(String[] args) { new ThreadsDemo1("Hello from X", 10).start(); new ThreadsDemo1("Hello from Y", 15).start(); } }
代码2:
package Threads; /** * Created by Frank */ public class ThreadsDemo2 implements Runnable { private String msg; private Thread t; private int count; public static void main(String[] args) { new ThreadsDemo2("Hello from X", 10); new ThreadsDemo2("Hello from Y", 15); } public ThreadsDemo2(String m, int n) { this.msg = m; count = n; t = new Thread(this); t.setName(msg + "runner Thread"); t.start(); } public void run() { while (count-- > 0) { System.out.println(msg); try { Thread.sleep(100); } catch (InterruptedException e) { return; } } System.out.println(msg + " all done."); } }
代码3:
package Threads; /** * Created by Frank */ public class ThreadsDemo3 { private int count; public static void main(String[] args) { new ThreadsDemo3("Hello from X", 10); new ThreadsDemo3("Hello from Y", 15); } public ThreadsDemo3(final String msg, int n) { this.count = n; Thread t = new Thread(new Runnable() { public void run() { while (count-- > 0) { System.out.println(msg); try { Thread.sleep(100); } catch (InterruptedException e) { return; } } System.out.println(msg + " all done."); } }); t.setName(msg + " runner Thread"); t.start(); } }
eclipse运行结果如下:
上述就是小编为大家分享的Java如何在不同线程中实现运行了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。