/*
继承Thread类,覆写run()方法
新建对象调用start()方法
*/
class MyThread extends Thread{
private String name;
MyThread(String name){
this.name = name;
}
public void run(){
for(int i=0;i<10;i++){
System.out.println("名字:"+name+i);
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread th1 = new MyThread("线程一");
MyThread th2 = new MyThread("线程二");
th1.start();
th2.start();
}
}
/*
运行结果:
名字:线程一0
名字:线程一1
名字:线程一2
名字:线程二0
名字:线程二1
名字:线程二2
名字:线程二3
名字:线程二4
名字:线程二5
名字:线程二6
名字:线程二7
名字:线程二8
名字:线程二9
名字:线程一3
名字:线程一4
名字:线程一5
名字:线程一6
名字:线程一7
名字:线程一8
名字:线程一9
*/
继承Thread类,覆写run()方法
新建对象调用start()方法
*/
class MyThread extends Thread{
private String name;
MyThread(String name){
this.name = name;
}
public void run(){
for(int i=0;i<10;i++){
System.out.println("名字:"+name+i);
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread th1 = new MyThread("线程一");
MyThread th2 = new MyThread("线程二");
th1.start();
th2.start();
}
}
/*
运行结果:
名字:线程一0
名字:线程一1
名字:线程一2
名字:线程二0
名字:线程二1
名字:线程二2
名字:线程二3
名字:线程二4
名字:线程二5
名字:线程二6
名字:线程二7
名字:线程二8
名字:线程二9
名字:线程一3
名字:线程一4
名字:线程一5
名字:线程一6
名字:线程一7
名字:线程一8
名字:线程一9
*/

本文通过一个具体的Java示例介绍了如何通过继承Thread类并重写run方法来创建和启动线程。示例中创建了两个线程,分别命名为“线程一”和“线程二”,并在run方法中输出了线程名称和计数。
1342

被折叠的 条评论
为什么被折叠?



