我可以在java中的线程中运行线程吗?
2022-09-03 04:21:11
在Java中,我需要实现一个在另一个类似类中扩展Thread的类。这可能吗?
我正在尝试执行的操作的一个示例是以下(简化的)代码段:
// 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
}
}
}
第二个线程直接在第一个线程中实现。此外,我想知道实现这样的互斥体是否可行。如果没有,有什么更好的(标准)方法来做到这一点吗?
提前感谢您。