我有这个线程成员
public int a;
我将线程 id 传递给静态函数,我想做类似的事情
function(long threadId, int a){
synchronized (threadId){
threadId.a = a;
threadId.notify();
}
}
我知道,线程 id 只是很长,它不会以这种方式工作,那么我如何在函数参数中引用带有 id 的线程?
我有这个线程成员
public int a;
我将线程 id 传递给静态函数,我想做类似的事情
function(long threadId, int a){
synchronized (threadId){
threadId.a = a;
threadId.notify();
}
}
我知道,线程 id 只是很长,它不会以这种方式工作,那么我如何在函数参数中引用带有 id 的线程?
I know, that threads id is just long and it wont work this way, so how can i reference thread with id i get in functions arguments?
You really can't do what you want to do. You could keep a map of thread-id to associated Thread
or Runnable
class yourself however and use it to lookup the id.
Thread thread = new MyThread();
thread.start();
idMap.put(thread.getId(), thread);
The right way to do this is to define your own class and deal with the object instead of the thread-id. It is recommended to implement Runnable
instead of extending Thread
. Something like:
public class MyRunnable impelments Runnable {
public int a;
...
public void run() {
// code run in the thread
synchronized (this) {
this.wait();
}
System.out.println(a);
}
}
Then you can do:
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
...
public void function(MyRunnable runnable, int a) {
synchronized (runnable){
runnable.a = a;
runnable.notify();
}
}
Better would be to have a setter on the MyRunnable
which encapsulates the process:
public synchronized void setA(int a) {
this.a = a;
this.notify();
}
An alternative would be to have the thread can share with the notifying thread a BlockingQueue
which saves you from the wait/notify. The main thread (or whomever is calling function
) then puts an entity into the queue and the thread pulls it out.