Thread类是在java.lang包中定义的。一个类只要继承了Thread类同时覆写了本类中的run()方法就能够实现多线程操做了,可是一个类只能继承一个父类,这是此方法的局限,php
下面看例子:html
class MyThread extends Thread{java
private String name;面试
public MyThread(String name) {spring
super();编程
this.name = name;性能优化
}微信
public void run(){多线程
for(int i=0;i<10;i++){架构
System.out.println("线程开始:"+this.name+",i="+i);
}
}
}
package org.thread.demo;
public class ThreadDemo01 {
public static void main(String[] args) {
MyThread mt1=new MyThread("线程a");
MyThread mt2=new MyThread("线程b");
mt1.run();
mt2.run();
}
}
可是,此时结果颇有规律,先第一个对象执行,而后第二个对象执行,并无相互运行。在JDK的文档中能够发现,一旦调用start()方法,则会经过JVM找到run()方法。下面启动
start()方法启动线程:
public class ThreadDemo01 {
public static void main(String[] args) {
MyThread mt1=new MyThread("线程a");
MyThread mt2=new MyThread("线程b");
mt1.start();
mt2.start();
}
};
这样程序能够正常完成交互式运行。那么为啥非要使用start();方法启动多线程呢?
在JDK的安装路径下,src.zip是所有的java源程序,经过此代码找到Thread中的start()方法的定义,能够发现此方法中使用了private native void start0();其中native关键字表示能够调用操做系统的底层函数,那么这样的技术成为JNI技术(java Native Interface)
·Runnable接口
在实际开发中一个多线程的操做不多使用Thread类,而是经过Runnable接口完成。
public void run();
}
例子:
class MyThread implements Runnable{
private String name;
public MyThread(String name) {
this.name = name;
}
public void run(){
for(int i=0;i<100;i++){
System.out.println("线程开始:"+this.name+",i="+i);
}
}
};
可是在使用Runnable定义的子类中没有start()方法,只有Thread类中才有。此时观察Thread类,有一个构造方法:public Thread(Runnable targer)此构造方法接受Runnable的子类实例,也就是说能够经过Thread类来启动Runnable实现的多线程。(start()能够协调系统的资源):
import org.runnable.demo.MyThread;
public class ThreadDemo01 {
public static void main(String[] args) {
MyThread mt1=new MyThread("线程a");
MyThread mt2=new MyThread("线程b");
new Thread(mt1).start();
new Thread(mt2).start();
}
}
· 两种实现方式的区别和联系:
在程序开发中只要是多线程确定永远以实现Runnable接口为主,由于实现Runnable接口相比
继承Thread类有以下好处:
->避免点继承的局限,一个类能够继承多个接口。
->适合于资源的共享
以卖票程序为例,经过Thread类完成:
class MyThread extends Thread{
private int ticket=10;
public void run(){
for(int i=0;i<20;i++){
if(this.ticket>0){
System.out.println("卖票:ticket"+this.ticket--);
}
}
}
};
下面经过三个线程对象,同时卖票:
public class ThreadTicket {
public static void main(String[] args) {
MyThread mt1=new MyThread();
MyThread mt2=new MyThread();
MyThread mt3=new MyThread();
mt1.start();//每一个线程都各卖了10张,共卖了30张票
mt2.start();//但实际只有10张票,每一个线程都卖本身的票
mt3.start();//没有达到资源共享
}
}
若是用Runnable就能够实现资源共享,下面看例子:
class MyThread implements Runnable{
private int ticket=10;
public void run(){
for(int i=0;i<20;i++){
if(this.ticket>0){
System.out.println("卖票:ticket"+this.ticket--);
}
}
}
}
package org.demo.runnable;
public class RunnableTicket {
public static void main(String[] args) {
MyThread mt=new MyThread();
new Thread(mt).start();//同一个mt,可是在Thread中就不能够,若是用同一
new Thread(mt).start();//个实例化对象mt,就会出现异常
new Thread(mt).start();
}
};
虽然如今程序中有三个线程,可是一共卖了10张票,也就是说使用Runnable实现多线程能够达到资源共享目的。
Runnable接口和Thread之间的联系:
public class Thread extends Object implements Runnable
发现Thread类也是Runnable接口的子类。