繁体   English   中英

如何从其他线程使用线程的方法?

[英]How can I use a thread's method from the other thread?

http://oreilly.com/catalog/expjava/excerpt/index.html上查看下面的教程后,我就写了。 我希望thread_B能够调用thread_A声明的方法thread_A

thread_A = new Thread(new Worker());
thread_A.start();

thread_B = new Thread(new Communicator(thread_A));
thread_B.start();

初始化线程并将其分配给类变量似乎工作正常。 但是,它似乎不允许我使用thread_A的方法。

//in thread_B, 
Thread worker;
public Communicator(Thread worker){
    this.worker = worker;
}
//if I want to call thead_A's method size()
public void run(){
    this.worker.queue.size(); //DOES NOT WORK
}

我只想让thread_B知道thread_A的队列信息。 解决这个问题的好方法是什么?

像这样做:

Worker w = new Worker();
thread_A = new Thread(w);
thread_B = new Thread(new Communicator(w));

并将Communicator的构造函数更改为使用Worker而不是Thread

属性队列不是Thread类的一部分。 它是Worker类的一部分吗?

如果是这样,那么代码需要写成类似的东西

worker = new Worker();
thread_A = new Thread(worker);
thread_A.start();

thread_B = new Thread(new Communicator(worker));
thread_B.start();


//in thread_B, 
Worker worker;
public Communicator(Worker worker){
    this.worker = worker;
}

//if I want to call thead_A's method size()
public void run(){
    this.worker.queue.size(); //print out queue size in thread_A
}

线程没有方法。 类有方法。 只需保留对您调用方法所需的任何对象引用的引用,并调用它。

暂无
暂无

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

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