Java中有两种方式实现多线程。
第一种继承线程类Thread,重写run方法。
public class MyThread extends Thread(){
public void run(){
for(int i=0;i<100;i++){
System.out.println("线程---"+i);
}
}
public static void main(String[] args) {
MyThread th1 = new MyThread ();
MyThread th2 = new MyThread ();
th1.start();
th2.start();
}
}
第二种实现Runnable接口。
public class TestRunnble implements Runnable{
@Override
public void run() {
for (int i=0;i<100;i++){
System.out.println(Thread.currentThread().getName()+i);
}
}
public static void main(String [] args){
TestRunnble tun1=new TestRunnble();
TestRunnble tun2=new TestRunnble();
Thread th1=new Thread(tun1);
Thread th2=new Thread(tun2);
th1.start();
th2.start();
}
}