当另一个线程中发生某些事情时,是否从主线程获取数据? [英] Get data from main thread when something happens in another?
问题描述
目前,我有一个运行套接字的线程侦听连接.收到连接后,它需要上传在主线程中收集的数据(即从主线程中获取数据).但是,我传递了一个Object的实例,但从未使用等待连接时收集的数据对其进行更新.
Currently I have a Thread running a Socket listening for connections. When it receives a connection, it needs to upload data gathered in the main thread (i.e. grab data from main thread). However I pass an instance of the Object, but it's never updated with the data that's collected while waiting for a connection.
是否有适当的方法来做到这一点?我已经四处搜寻,似乎找不到具体答案.
Is there a proper way to do this? I've googled around and can't seem to find a concrete answer.
有人能指出我正确的方向吗?
Could someone point me in the right direction?
希望这是有道理的,但我将尝试通过示例进行解释.
Hopefully this makes sense, but i'll try to explain more with an examples.
class MainThread {
private void MainThread() {
SomeObj obj = new SomeObj("DATA Needed");
SecondThread second = new SecondThread(obj);
second.start();
}
}
class SecondThread extends Thread {
SomeObj obj;
public void SecondThread(Object obj) {
this.obj = obj;
}
public void run() {
//Listening for connection
//Connection get!
//Get updated data (Object obj) from main thread.
//Upload
}
}
感谢您能给我任何帮助.如果我要完全解决这个问题,请告诉我!我宁愿学习并获得答案,而不是仅仅获得答案.
I appreciate any help you can give me. Please let me know if I am approaching this completely wrong! I would rather learn AND get answers than just get answers.
非常感谢!
推荐答案
收到连接后,它需要上传在主线程中收集的数据(即从主线程中获取数据).
When it receives a connection, it needs to upload data gathered in the main thread (i.e. grab data from main thread).
这没有意义,因为您没有从 Threads 获取信息,而是获得了信息并与 Objects 进行了通信.那是很大的不同.您需要将需要信息的对象的实例传递到需要此信息的第二个对象中,或者作为其构造函数中的参数.然后,您将使用该实例在SecondThread类中设置一个字段,然后可以在其上调用方法.
This doesn't make sense as you don't get information from Threads, you get information and communicate with Objects. That's a big difference. You need to pass an instance of the object that you need information from into the second object that needs this information, perhaps as a parameter in its constructor. Then you would set a field in your SecondThread class with this instance and you can call methods on it.
即
class MainThread {
private void MainThread() {
SomeType obj = new SomeType("DATA Needed");
SecondThread second = new SecondThread(obj);
second.start();
}
}
class SecondThread extends Thread {
SomeType obj;
public SecondThread(SomeType obj) {
this.obj = obj;
}
public void run() {
// can call methods on obj here
}
}
希望您实际上并没有使用Object类型,而是使用了一种更具体的对象类型,对吧?
Hopefully you're not actually using an Object type but rather a much more specific type of object, right?
这篇关于当另一个线程中发生某些事情时,是否从主线程获取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!