本文介绍了Java,线程,仅run()块会成为线程的一部分,还是start()调用后的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Java启动线程,我想对start()/run()在我所处的情况下的行为有一个清晰的认识.

I'm starting Threads in java, I would like to have a clear idea of how start()/run() acts in my situation.

我创建了一个名为t的线程,并放置了t.start()后跟一个for循环.

I've created a thread calle t, and I've placed t.start() followed by a for cycle.

for循环是thread.t的一部分还是主线程的一部分?

Will the for cycle be part of the thread.t or is it part of the main thread??

class Job implements Runnable{
Thread t;

    Job(String tName){
        t=new Thread(this, tName);
        System.out.println("This is thread: "+t.getName());
        t.start();
        System.out.println("This is the end of constructor");
        try{   /*<<<<<<<------------WILL THIS RUN in my MAIN thread or in the t thread??*/
            for(int i=0;i<5;i++){
                System.out.println("xxxThis is the count i value: "+i+" "+ t.getName());
                Thread.sleep(1000);
            }
        }
        catch(InterruptedException e){
        System.out.println("The thread has been interrupted");
        }

    }

    public void run(){
        System.out.println("This is the start of RUN()");
        try{
            for(int i=0;i<5;i++){
                System.out.println("This is the count i value: "+i+" "+ t.getName());
                Thread.sleep(1000);
            }
        }
        catch(InterruptedException e){
        System.out.println("The thread has been interrupted");
        }
        finally{
            System.out.println("Fnally block reached: "+t.getName());
        }
    }
}

推荐答案

start()方法产生一个新的执行线程,并在该线程中执行run方法.在这种情况下,线程将具有其自己的call stack.而直接调用run()方法不会产生新线程.相反,这将导致run()方法在具有旧调用堆栈的当前执行线程中执行.

start() method spawns a new thread of execution and executes the run method in that thread. In this case , the thread will have its own call stack. Whereas, calling run() method directly doesn't spawns a new thread. Instead this will cause the run() method to execute in the current executing thread having old call stack.

for循环将是Thread的一部分(如果您在主线程中创建Job实例,则为main线程),从中生成线程t.而且,如果要确认,则只需打印thread的名称,该名称将使用Thread.currentThread().getName()执行for循环.示例:

The for cycle will be part of the Thread(in your case is main thread if you create Job instance in main thread) from which Thread t is spawned. And if you want to confirm then simply print the name of thread which is executing that for loop using Thread.currentThread().getName() . Example:

try{   /*<<<<<<<------------WILL THIS RUN in my MAIN thread or in the t thread??*/
    System.out.println(Thread.currentThread().getName()+" is executing this for loop");
    for(int i=0;i<5;i++){
        System.out.println("xxxThis is the count i value: "+i+" "+ t.getName());
        Thread.sleep(1000);
    }

这篇关于Java,线程,仅run()块会成为线程的一部分,还是start()调用后的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 06:43