Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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 :)

like image 786
user1232948 Avatar asked Nov 26 '25 10:11

user1232948


1 Answers

Lots of options :) By default, java collections aren't syncronized:

You could make a LinkedBlockingQueue in a static variable/class:

  • http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/LinkedBlockingQueue.html

You could wrap one of the many java collections with the following:

  • Collections.synchronizedMap(..)
  • Collections.synchronizedList(..)
  • Collections.synchronizedSet(..)

If you don't mind some complication, but are concerned about GC overhead, use Exchanger (I'd recommend this for your situation):

  • http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Exchanger.html

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):

  • http://code.google.com/p/disruptor/
like image 54
Jonathan S. Fisher Avatar answered Nov 29 '25 01:11

Jonathan S. Fisher