您的位置:首页 > 编程语言 > Java开发

Java中start和run方法的区别

2013-07-21 16:58 309 查看
一.问题引入

        说到这两个方法就不得不说多线程,说到多线程就不得不提实现多线程的两种方式继承Thread类和实现Runable接口,下面先看这两种方式的区别。

二. Java中实现多线程的两种方式

继承Thread类
/**
* 使用Thread类模拟4个售票窗口共同卖100张火车票的程序,实际上是各卖100张
*/
public class ThreadTest {

public static void main(String[] args){
new MyThread().start();
new MyThread().start();
new MyThread().start();
new MyThread().start();
}

//也可以把类写在外边
public static class MyThread extends Thread{
private int tickets=100;
public void run() {
while(tickets>0){
System.out.println(this.getName()+"卖出第【"+tickets--+"】张火车票");
}
}
}
}


/**
* 使用Thread类模拟4个售票窗口共同卖100张火车票的程序,实际上是各卖100张
*/
public class ThreadTest {

public static void main(String[] args){
new MyThread().start();
new MyThread().start();
new MyThread().start();
new MyThread().start();
}
}
class MyThread extends Thread{
private int tickets=100;
public void run() {
while(tickets>0){
System.out.println(this.getName()+"卖出第【"+tickets--+"】张火车票");
}
}
}





      2.  实现Runable接口

/**
* 使用Runnable接口模拟4个售票窗口共同卖100张火车票的程序
*/
public class RunnableTest {

public static void main(String[] args) {
Runnable runnable=new MyThread();
new Thread(runnable).start();
new Thread(runnable).start();
new Thread(runnable).start();
new Thread(runnable).start();
}

public static class MyThread implements Runnable{
private int tickets=100;
public void run() {
while(tickets>0){
System.out.println(Thread.currentThread().getName()+"卖出第【"+tickets--+"】张火车票");
}
}
}
}





不管采用哪种方式,覆盖run方法时既可以用内部类也可以用外部类,不过一般采用内部类。

      3.  两种方式的比较

实际中往往采用实现Runable接口,一方面因为java只支持单继承,继承了Thread类就无法再继续继承其它类,而且Runable接口只有一个run方法;另一方面通过结果可以看出实现Runable接口才是真正的多线程……

三.两种方法的区别

       1) start:

用start方法来启动线程,真正实现了多线程运行,这时无需等待run方法体代码执行完毕而直接继续执行下面的代码。通过调用Thread类的start()方法来启动一个线程,这时此线程处于就绪(可运行)状态,并没有运行,一旦得到cpu时间片,就开始执行run()方法,这里方法 run()称为线程体,它包含了要执行的这个线程的内容,Run方法运行结束,此线程随即终止。

       2) run:

run()方法只是类的一个普通方法而已,如果直接调用Run方法,程序中依然只有主线程这一个线程,其程序执行路径还是只有一条,还是要顺序执行,还是要等待run方法体执行完毕后才可继续执行下面的代码,这样就没有达到写线程的目的。总结:调用start方法方可启动线程,而run方法只是thread的一个普通方法调用,还是在主线程里执行。这两个方法应该都比较熟悉,把需要并行处理的代码放在run()方法中,start()方法启动线程将自动调用 run()方法,这是由jvm的内存机制规定的。并且run()方法必须是public访问权限,返回值类型为void.。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: