简体   繁体   中英

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

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:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM