Java如何在不同线程中实现运行
这期内容当中小编将会给大家带来有关Java如何在不同线程中实现运行,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
10年积累的成都做网站、网站制作、成都外贸网站建设经验,可以快速应对客户对网站的新想法和需求。提供各种问题对应的解决方案。让选择我们的客户得到更好、更有力的网络服务。我虽然不认识你,你也不认识我。但先做网站设计后付款的网站建设流程,更有延吉免费网站建设让你可以放心的选择与我们合作。
具体如下:
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如何在不同线程中实现运行了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注创新互联行业资讯频道。
当前标题:Java如何在不同线程中实现运行
标题链接:http://lswzjz.com/article/pjgcdd.html