简体   繁体   English

我可以在java中的线程中运行一个线程吗?

[英]Can I run a thread within a thread in java?

In Java I have the necessity of implementing a class that extends Thread within another similar class. 在Java中,我有必要实现一个在另一个类似的类中扩展Thread的类。 Is that possible? 那可能吗?

An example of what I am trying to do is the following (simplified) snippet: 我想要做的一个例子是以下(简化)片段:

// The first layer is a Thread
public class Consumer extends Thread {

    // Variables initialized correctly in the Creator
    private BufferManager BProducer = null;

    static class Mutex extends Object {}
    static private Mutex sharedMutex = null;


    public Consumer() {
        // Initialization of the thread
        sharedMutex = new Mutex();

        BProducer = new BProducer(sharedMutex);
        BProducer.start();
    }


    public void run() {

        int data = BProducer.getData();

        ///// .... other operations
    }


    ////// ...... some code

    // Also the second layer is a Thread
    private class BufferManager extends Thread {

        Mutex sharedMutex;
        int data;

        public BufferManager(Mutex sM) {
            sharedMutex = sM;
        }

        public int getData(Mutex sM) {
            int tempdata;
            synchronized(sharedMutex) {
                tempdata = data;
            }
            return tempdata;
        }

        public void run() {
            synchronized(sharedMutex) {
                data = getDataFromSource();
            }
            ///// .... other operations on the data
        }
    }
}

The second Thread is implemented directly inside the First one. 第二个Thread直接在第一个Thread中实现。 Moreover I'd like to know if implementing a Mutex like that will work. 此外,我想知道实现这样的Mutex是否有效。 If not, there's any better (standard) way to do it? 如果没有,还有更好的(标准)方法吗?

Thank you in advance. 先感谢您。

The Thread is not run 'within', but rather side-by-side. Thread不是在'内部'运行,而是并排运行。

So yes, you can start up another Thread to run side-by-side with your other two Thread 's. 所以,是的,你可以启动另一个Thread与你的另外两个Thread并排运行。 As a matter of fact, any Thread can start another Thread (so long as the OS allows it). 事实上,任何Thread都可以启动另一个Thread (只要操作系统允许它)。

Yes, this should work and the shared Mutex should do it's job. 是的,这应该工作,共享互斥锁应该做它的工作。 Out of paranoia, I'd make both the mutex declarations final to avoid any weird "escaping" issues. 出于偏执,我会将互斥声明作为final以避免任何奇怪的“逃避”问题。 eg 例如

final Mutex sharedMutex;

One suggestion: maybe this is my style, but for code like this I seldom extend Thread . 一个建议:也许这是我的风格,但对于像这样的代码,我很少扩展Thread Just implement Runnable instead. 只需实现Runnable IMO it's a bit less confusing (YMMV here). IMO它有点混乱(YMMV在这里)。 Plus, when you start using advanced concurrency utilities like Executor , they deal with Runnables , not Threads. 另外,当您开始使用像Executor这样的高级并发实用程序时,它们会处理Runnables ,而不是Threads。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM