Java实现在不同线程中运行的代码实例

网友投稿 195 2023-05-24


Java实现在不同线程中运行的代码实例

本文实例讲述了java实现在不同线程中运行的代码。分享给大家供大家参考,具体如下:

start()方法开始为一个线程分配CPU时间,这导致对run()方法的调uoSIeXWAn用。

代码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 ThreauoSIeXWAnd");

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(finalhttp:// 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程序设计有所帮助。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java数据结构与算法之选择排序(动力节点java学院整理)
下一篇:SpringBoot中自定义注解实现控制器访问次数限制实例
相关文章

 发表评论

暂时没有评论,来抢沙发吧~