Reputation: 29
I have 10 identical threads (differentiated only by primary key from 1 to 10) that I create in the main class. In each thread I need to read field in the previous thread i.e. in thread 5 I need to read this field in thread 4. The question is how can I do it?
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.
Thanks in advance :)
Upvotes: 3
Views: 5098
Reputation: 8807
Lots of options :) By default, java collections aren't syncronized:
You could make a LinkedBlockingQueue in a static variable/class:
You could wrap one of the many java collections with the following:
If you don't mind some complication, but are concerned about GC overhead, use Exchanger (I'd recommend this for your situation):
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):
Upvotes: 7