时间:2021-05-19
本文实例讲述了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程序设计有所帮助。
声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。
Java理解ThreadLocal摘要: ThreadLocal又名线程局部变量,是Java中一种较为特殊的线程绑定机制,用于保证变量在不同线程间的隔离性,以
Java多线程实例3种实现方法Java中的多线程有三种实现方式:1.继承Thread类,重写run方法。Thread本质上也是一个实现了Runnable的实例,
本文实例分析了java多线程中的volatile和synchronized用法。分享给大家供大家参考。具体实现方法如下:复制代码代码如下:packagecom.
本文实例为大家分享了Java实现线程间通信的具体代码,供大家参考,具体内容如下Java代码(使用了2个内部类):packageThreads;importjav
本文实例讲述了Java实现的两个线程同时运行。分享给大家供大家参考,具体如下:/***两个案例同时运行案例*1:这个两个线程并不是有规律的运行而是有没有规律的交