java中run()和start()的区别

本文详细解析了Java多线程程序的运行过程,包括如何通过`Thread`类实现多线程,以及如何通过`start()`和`run()`方法控制线程的执行流程。通过代码示例展示了在多线程环境下变量的并发访问情况,并对比了两种不同方法的执行结果,揭示了Java线程执行机制的本质。
class NewThread implements Runnable {
Thread t;
public NewThread() {
t = new Thread(this,"Demo thread");
System.out.println("Child thread : " + t);
t.run();
}
public void run(){
try{
for( int i = 5; i > 0; i --){
System.out.println("Child thread :" + i);
Thread.sleep(500);
}

}catch(InterruptedException e){
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");

}
}

public class TestDemo{
public static void main(String args[]){
new NewThread();
try{
for( int i = 5; i > 0; i --){
System.out.println("Main thread :" + i);
Thread.sleep(1000);
}
}catch(InterruptedException e){
System.out.println("Main interrupted.");
}
System.out.println("Exiting Main thread.");
}
}

这是一个实现多线程的程序,运行结果如下:
Child thread : Thread[Demo thread,5,main]
Main thread :5
Child thread :5
Child thread :4
Main thread :4
Child thread :3
Child thread :2
Main thread :3
Child thread :1
Exiting child thread.
Main thread :2
Main thread :1
Exiting Main thread.

试想,如果把 start()改成run()会出现什么结果?
修改之后运行结果:
Child thread : Thread[Demo thread,5,main]
Child thread :5
Child thread :4
Child thread :3
Child thread :2
Child thread :1
Exiting child thread.
Main thread :5
Main thread :4
Main thread :3
Main thread :2
Main thread :1
Exiting Main thread.
程序运行成为了单线程顺序执行。为什么?
start方法:用来启动一个线程, 这时此线程是处于就绪状态, 并没有运行。 然后通过此Thread类调用方法run()来完成其运行操作的, 这里方法run()称为线程体, 它包含了要执行的这个线程的内容, run方法运行结束, 此线程终止, 而CPU再运行其它线程,
直接用run方法: 这只是调用一个方法而已, 程序中依然只有主线程--这一个线程, 其程序执行路径还是只有一条, 这样就没有达到写线程的目的。
记住:线程就是为了更好地利用CPU,提高程序运行速率的!

让一个类继承Thread,重写run()方法,然后调用时使用:new ThreadImp().start()方法

来启动该类的实例!不要用new ThreadImp().run() !!!

来自?http://libingye.iteye.com/blog/930615

Java中,run方法start方法存在明显区别: - **线程执行方式**:start方法是多线程编程的核心,它会启动一个新线程,使该线程的运行与其他线程并行进行;而直接调用run方法仅仅是在当前线程中顺序执行run方法中的代码,不会产生新的线程执行流。例如,若没有调用线程的start方法,而是在应用代码中直接调用run方法,那么这个线程的run方法运行在当前线程(即run方法的调用方所在的线程)之中,并非运行在其自身的线程里,这违背了创建线程的初衷,没有创建新线程 [^1][^3]。 - **方法性质**:run方法只是类的一个普通方法。如果直接调用run方法,程序中依然只有主线程这一个线程,程序执行路径只有一条,需顺序执行,要等待run方法体执行完毕后才可继续执行下面的代码,无法达到多线程编程的目的。而调用start方法才能真正启动线程 [^1][^4]。 以下是示例代码: ```java public class ThreadDemo { public static void main(String[] args) { // 创建实现Runnable接口的线程实例 RunnableThread runnableThread = new RunnableThread(); // 直接调用run方法,在主线程中顺序执行 runnableThread.run(); // 创建线程对象并传入Runnable实例 Thread thread = new Thread(runnableThread); // 调用start方法启动新线程 thread.start(); } } class RunnableThread implements Runnable { private int count = 10; @Override public void run() { while (count > 0) { System.out.println(Thread.currentThread().getName() + "-------" + count--); } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值