(1)Thread子类实现多线程,程序代码: package a; public class c extends Thread { int threadnum; int count = 5; public c(int num){ threadnum = num; System.out.println("创建线程"+threadnum); } public void run(){ while(count>0) System.out.println("线程"+threadnum+"计数"+(count--)); } public static void main(String[] args) { c a = new c(1); c b = new c(2); c c = new c(3); a.start(); b.start(); c.start(); } } 运行结果: (2)用实现Runnable接口的方法改写小题(1)的程序,程序代码:
时间: 2023-05-17 11:04:01 浏览: 73
Java多线程程序设计-JSP教程,Java技巧及代码
5星 · 资源好评率100%
public class MyRunnable implements Runnable {
int threadnum;
int count = 5;
public MyRunnable(int num){
threadnum = num;
System.out.println("创建线程" + threadnum);
}
public void run(){
while(count>0)
System.out.println("线程" + threadnum + "计数" + (count--));
}
public static void main(String[] args) {
Thread a = new Thread(new MyRunnable(1));
Thread b = new Thread(new MyRunnable(2));
Thread c = new Thread(new MyRunnable(3));
a.start();
b.start();
c.start();
}
}
运行结果:
创建线程1
创建线程2
创建线程3
线程1计数5
线程2计数5
线程3计数5
线程1计数4
线程2计数4
线程3计数4
线程1计数3
线程2计数3
线程3计数3
线程1计数2
线程2计数2
线程3计数2
线程1计数1
线程2计数1
线程3计数1
阅读全文