方法1:通过Thread继承类,修改run()方法来实现多线程。

package 线程的创建1;

public class example1 {

public static void main(String[] args) {
MyThread myThread=new MyThread();//创建线程MyThread的线程对象
myThread.start(); //开启线程
while(true){
System.out.println("main()方法在运行");
}
}

}


package 线程的创建1;

public class MyThread extends Thread{
public void run(){
while(true){
System.out.println("MyThread类的run()方法在运行");
}
}
}



通过Thread继承类实现了多线程,但是这种方式有一定的局限性。
  因为java只支持单继承,一个类一旦继承父类就无法继承Thread类
  为了克服这种弊端,Thread类提供了另外一种构造方法Thread(Runnable target)
  其中runnable是一个接口,它只有一个run()方法。


方法2:

public class example2 {

public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread myThread=new MyThread(); //创建MyThread的实例对象
Thread thread=new Thread(myThread); //创建线程对象
thread.start(); //开启线程,执行run()方法
while(true){
System.out.println("main()方法在运行");
}
}
}


package 线程的创建2;

public class MyThread implements Runnable{
public void run()
{
while(true){
System.out.println("MyThread类的run()方法在运行");
}
}
}


运行结果:

多线程之线程创建的两种方法(Java)_构造方法