java--(多线程创建的两种方式Thread类和Runnable接口)

(一)继承Thread类创建多线程----单线程

下面的代码是一个死循环,但是不会执行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()方法在运行");
		}
	}
}



评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值