[英]Passing variables between threads in Java
I have 10 identical threads (differentiated only by primary key from 1 to 10) that I create in the main class. 我在主类中创建了10个相同的线程(仅通过主键从1到10进行了区分)。 In each thread I need to read field in the previous thread ie in thread 5 I need to read this field in thread 4. The question is how can I do it? 在每个线程中,我需要读取前一个线程中的字段,即在线程5中,我需要在线程4中读取此字段。问题是我该怎么办?
public class Player extends Thread {
private Integer playerNumber;
public char lastDigit;
public Player(Integer playerNumber) {
super();
this.playerNumber = playerNumber;
}
public synchronized char getDigit(){
return this.lastDigit;
}
public synchronized void setDigit(char digit){
massage += digit;
this.lastDigit = digit;
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void run(){
}
I need to read the lastDigit field. 我需要阅读lastDigit字段。
Thanks in advance :) 提前致谢 :)
Lots of options :) By default, java collections aren't syncronized: 许多选项:)默认情况下,java集合不同步:
You could make a LinkedBlockingQueue in a static variable/class: 您可以在静态变量/类中创建LinkedBlockingQueue:
You could wrap one of the many java collections with the following: 您可以使用以下方法包装许多Java集合之一:
If you don't mind some complication, but are concerned about GC overhead, use Exchanger (I'd recommend this for your situation): 如果您不介意复杂性,但担心GC开销,请使用Exchanger(我会根据您的情况建议这样做):
If you reallly want to go all out and performance is a major concern, you could use the Disrupter framework (not for the feint of heart): 如果您真的想全力以赴,而性能是一个主要问题,则可以使用Disrupter框架(不是冒犯性的):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.