(一)继承Thread类创建多线程----单线程
(二)通过继承Thread类实现多线程:
如果希望(一)中的两个循环打印语句都能够执行的话,那么就需要实现多线程。为此jdk提供了一个多线程类Thread,通过继承Thread类,并重写Thread类中的run()方法便可以实现多线程。在Thread类中,提供了一个start()方法用于启动新线程,线程启动后,系统就会自动调用run()方法。
(三)实现Runnable接口创建多线程
在(二)中通过继承Thread类实现多线程,但是这种方式有一定的局限性。因为在java中只支持单继承,一个类一旦继承了某个父类就无法再继承Thread类,比如学生类Student继承了person类,就无法再继承Thread类创建的线程。为了克服这种弊端,Thread类提供了另外一种构造方法Thread(Runnable target),其中Runnable是一个接口,它只有一个run()方法。当通过Thread(Runnable target)构造方法创建一个线程对象时,只需该方法传递一个实现了Runnable接口的实例对象,这样创建的线程将调用实现了Runnable接口中的run()方法作为运行代码,二不需要调用Thread类中的run()方法。
下面的代码是一个死循环,但是不会执行main里面的循环语句,而是run()里面的语句,这是因为该程序是一个单线程程序,当调用MyThread类的run()方法时,遇到死循环,循环一直进行。因此,MyThread类的打印语句将永远执行,而main()方法中的打印语句无法得到执行。
package test;
public class example {
public static void main(String[] args){
MyThread myThread=new MyThread();
myThread.run();
while(true)
{
System.out.println("Main方法在运行");
}
}
}
class MyThread{
public void run(){
while(true){
System.out.println("MyThread类的run()方法在运行");
}
}
}
(二)通过继承Thread类实现多线程:
如果希望(一)中的两个循环打印语句都能够执行的话,那么就需要实现多线程。为此jdk提供了一个多线程类Thread,通过继承Thread类,并重写Thread类中的run()方法便可以实现多线程。在Thread类中,提供了一个start()方法用于启动新线程,线程启动后,系统就会自动调用run()方法。
package test;
public class example {
public static void main(String[] args){
MyThread myThread=new MyThread();
myThread.start();
while(true)
{
System.out.println("Main方法在运行");
}
}
}
class MyThread extends Thread{
public void run(){
while(true){
System.out.println("MyThread类的run()方法在运行");
}
}
}
(三)实现Runnable接口创建多线程
在(二)中通过继承Thread类实现多线程,但是这种方式有一定的局限性。因为在java中只支持单继承,一个类一旦继承了某个父类就无法再继承Thread类,比如学生类Student继承了person类,就无法再继承Thread类创建的线程。为了克服这种弊端,Thread类提供了另外一种构造方法Thread(Runnable target),其中Runnable是一个接口,它只有一个run()方法。当通过Thread(Runnable target)构造方法创建一个线程对象时,只需该方法传递一个实现了Runnable接口的实例对象,这样创建的线程将调用实现了Runnable接口中的run()方法作为运行代码,二不需要调用Thread类中的run()方法。
package test;
public class example {
public static void main(String[] args){
MyThread myThread=new MyThread();
Thread thread=new Thread(myThread);
thread.start();
while(true)
{
System.out.println("Main方法在运行");
}
}
}
class MyThread implements Runnable{
public void run(){
while(true){
System.out.println("MyThread类的run()方法在运行");
}
}
}