- 两种实现方式:一、实现Runnable接口。二、继承Thread类。
-
重写run()方法,调用start()方法。
一、实现Runnable接口
class T implements Runnable{
int a=0;
String name;
public T(String str) {
this.name=str;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(a<10) {
a++;
System.out.println(name+" : "+a);
}
}
}
public class Test{
public static void main(String args[]) {
T t1=new T("线程1");
T t2=new T("线程2");
Thread w1=new Thread(t1);
Thread w2=new Thread(t2);
w1.start();
w2.start();
}
}
二、继承Thread类
class T extends Thread{
int a=0;
String name;
public T(String str) {
this.name=str;
}
@Override
public void run() {
// TODO Auto-generated method stub
while(a<10) {
a++;
System.out.println(name+" : "+a);
}
}
}
public class Test{
public static void main(String args[]) {
T t1=new T("线程1");
T t2=new T("线程2");
t1.start();
t2.start();
}
}
来源:https://www.cnblogs.com/ruowei/p/10851990.html