通过继承Thread类实现 多线程-
public class Hello{ public static void main(String args[]){ MyThread tr1 = new MyThread("线程1"); MyThread tr2 = new MyThread("线程2"); MyThread tr3 = new MyThread("线程3"); tr1.start(); tr2.start(); tr3.start(); } } class MyThread extends Thread{ private String name; public MyThread(String name){ this.name = name; } @Override public void run() { for(int x=0; x<10; x++){ System.out.println(this.name+",x="+x); } } }
通过Runnable接口实现多线程
public class Hello{
public static void main(String args[]){
MyThread mt1 = new MyThread("线程A");
MyThread mt2 = new MyThread("线程B");
MyThread mt3 = new MyThread("线程C");
Thread tr1 = new Thread(mt1);
Thread tr2 = new Thread(mt2);
Thread tr3 = new Thread(mt3);
tr1.start();
tr2.start();
tr3.start();
}
}
class MyThread extends Thread{
private String name;
public MyThread(String name){
this.name = name;
}
@Override
public void run() {
for(int x=0; x<10; x++){
System.out.println(this.name+",x="+x);
}
}
}