从另一个类调用扩展Thread的类的方法

从另一个类调用扩展Thread的类的方法

本文介绍了从另一个类调用扩展Thread的类的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个天真的问题,但是我想了解Java多线程背后的基本工作原理.考虑下面的代码,并说A在主线程中执行,它开始执行另一个在类B中定义的工作线程.我想知道是否可以并行执行从A调用的B.func1和B的运行方法. ?

I know this is a bit naive question but I want to understand the basic working principle behind multi-threading in java. Consider the following code and say A is executed in Main thread and it starts execution of another worker thread ,defined in class B. I want to know that can B.func1 called from A and run method of B, be executed in parallel or not?

public class A {
    public static void main(String[] args) {
        B obj = new B();
        obj.start();
        obj.func1();
    }
}

public class B extends Thread {
    public B() {
        //constructor
    }
    public void run() {
        while(true) {
            //do somethings
        }
    }
    public void func1() {
        //do someotherthings
    }
}

推荐答案

方法调用背后没有魔术.如果从线程调用方法,则在完全相同的线程中调用该方法.因此,由于从main调用了obj.func1(),因此它将在主线程中运行.属于哪个类或是否扩展Thread都无关紧要.

There is no magic behind a method call. If you call method from a thread, it is called in exactly the same thread. So since obj.func1() is called from main, it will be run in the main thread. It doesn't matter which class it belongs to or whether or not it extends Thread.

新线程通过执行run开始.从run等调用的所有内容都将与main并行执行.

The new thread starts by executing run. Everything called from run and so on will be executed in parallel to main.

这篇关于从另一个类调用扩展Thread的类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 05:44