A strange problem with a simple multi-threaded program in Java

I'm just starting to play with multi-threaded programming. I would like my program to alternately display the characters "-" and "+", but this is not so. My task is to use a keyword synchronized. As far as I know:

class FunnyStringGenerator{

    private char c;

    public FunnyStringGenerator(){
        c = '-';
    }

    public synchronized char next(){

        if(c == '-'){
            c = '+';
        }
        else{
            c = '-';
        }

        return c;
    }
}

class ThreadToGenerateStr implements Runnable{

    FunnyStringGenerator gen;

    public ThreadToGenerateStr(FunnyStringGenerator fsg){
        gen = fsg;
    }

    @Override
    public void run() {
        for(int i = 0; i < 10; i++){

            System.out.print(gen.next());
        }
    }


}

public class Main{


    public static void main(String[] args) throws IOException {

        FunnyStringGenerator FSG = new FunnyStringGenerator();

        ExecutorService exec = Executors.newCachedThreadPool();

        for(int i = 0; i < 20; i++){
            exec.execute(new ThreadToGenerateStr(FSG));
        }

    }

}

EDIT: I am also testing Thread.sleepin a run method instead of a loop for.

+3
source share
3 answers

Your unit synchronizedis FunnyStringGenerator.next()working fine. He will return '+'and '-'take turns.

However, you have a race condition in ThreadToGenerateStr.run():

System.out.print(gen.next());

This is equivalent to:

char c = gen.next(); // Synchronized
System.out.print(c); // Not synchronized

The problem occurs when:

  • Thread 1 calls gen.next (), getting the result '-'
  • Thread 2 gen.next(), "+"
  • Thread 2 System.out.print(), '+'
  • 1 System.out.print(), '-'

"+" "-" .

, :

  • gen.next(), System.out.print() synchronized ( dogbane)
  • gen.next()
  • gen.next() BlockingQueue - .
+5

:

        synchronized (gen) {
            System.out.print(gen.next());
        }

, c .

:

char n = gen.next();
System.out.print(n);
+3

Please use two streams to print each character and use this concept of waiting and notification.

-1
source

Source: https://habr.com/ru/post/1785757/


All Articles