编写一个程序,该程序能够生成3个线程,每个线程从1输出到10,要求用两种方法实现;
public class Thread1{
public static class testThread extends Thread{
@Override
public void run() {
super.run();
for (int i = 1; i <= 10; i++) {
System.out.println(Thread.currentThread().getName()+": "+i);
}
}
}
public static void main(String[] args){
for(int i=0; i<3; i++){
new testThread().start();
System.out.println("MainThread:"+i);
}
}
}
和继承自Thread类差不多,不过实现Runnable后,还是要通过一个Thread来启动。
public class Thread2 {
public static class testThread2 implements Runnable{
@Override
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println(Thread.currentThread().getName()+": "+i);
}
}
}
public static void main(String[] args){
for(int i=0; i<3; i++){
testThread2 thread = new testThread2();
new Thread(thread).start();
System.out.println("MainThread:"+i);
}
}
}
对于这两种创建方式,推荐使用第二种方式,即通过实现Runnable接口来创建线程。因为继承只能单继承,而实现可以多实现,且实现的方式有利于减小程序之间的耦合。
本文地址:https://blog.csdn.net/yh991314/article/details/107342964
如对本文有疑问, 点击进行留言回复!!
before社区电量是什么意思 Before社区电量获得方法
RecycleView入门详解(教你全面掌握RecycleView用法)
动态权限请求框架RxPermissions(几行代码搞定权限)
URL路径@PathVariable出现点号“.“时值遭截断问题
网友评论