java中thread的start,和run

1.start()方法来启动线程,真正实现了多线程运行,这时无需等待run方法体代码执行完毕而直接继续执行下面的代码:

通过调用Thread类的start()方法来启动一个线程, 这时此线程是处于就绪状态, 并没有运行。 然后通过此Thread类调用方法run()来完成其运行操作的, 这里方法run()称为线程体, 它包含了要执行的这个线程的内容, Run方法运行结束, 此线程终止, 而CPU再运行其它线程,

2.run()方法当作普通方法的方式调用,程序还是要顺序执行,还是要等待run方法体执行完毕后才可继续执行下面的代码:

而如果直接用Run方法, 这只是调用一个方法而已, 程序中依然只有主线程--这一个线程, 其程序执行路径还是只有一条, 这样就没有达到写线程的目的。

---------------------------------------------------------------------------

package waitio;

public class Thread1 extends Thread{
    public static void main(String[] args) {
        Thread1 one = new Thread1();
        one.setName("one : ");
        Thread1 two = new Thread1();
        two.setName("two : ");
//线程1开启 one.start();
//线程2 开启 two.start(); /* one.run();
//这是方法调用,而不是开启一个线程 two.run();*/ } @Override public void run() { super.run(); for (int i = 0; i < 10; i++) { System.out.println(currentThread().getName()+" -- "+i); } } }

输出:

one : -- 0

one : -- 1

one : -- 2

one : -- 3

one : -- 4

one : -- 5

one : -- 6

two : -- 0

two : -- 1

two : -- 2

two : -- 3

two : -- 4

two : -- 5

two : -- 6

two : -- 7

two : -- 8

two : -- 9

one : -- 7

one : -- 8

one : -- 9

In Example one the threads will run sequentially:

first, thread number one runs, when it exits the thread number two starts.

In Example two both threads start and run simultaneously.

Conclusion: the start() method call run() method asynchronously (does not wait for any result, just fire up an action), while we run run() method synchronously - we wait when it quits and only then we can run the next line of our code.