Problem in thread execution, using flags

6

I'm having problems understanding the code completely because I'm new to using java in thread. What code will do is to control the flow by doing 55 iterations by dividing the thread and main program:

Resultado:
Main Thread.: 1
New Thread..: 2
Main Thread.: 3
New Thread..: 4
...
Main Thread.: 51
New Thread..: 52
Main Thread.: 53
New Thread..: 54

So far so good, the problem is, when in certain execution the program goes into some infinite loop and does not stop executing another time it completes the execution, I wanted help to understand this problem.

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 /
package testando;

/*
 *
 * @author Márcio
 */
public class Testando {
static int value = 0;
static int flag = 1;

@SuppressWarnings("empty-statement")
    public static void main(String[] args) {

                class MyThread extends Thread {

                        @Override
                        public void run() {
                                while(flag == 1);
                                while(++value < 55) {
                                        System.out.println("New Thread..: " + value);
                                        flag = 1;
                                        while( value < 55 && flag == 1);
                                }
                        }
                }

                Thread thread1 = new MyThread();
                thread1.start();
                System.out.println(flag == 0);
                while(flag == 0);
                while(++value < 55) {
                        System.out.println("Main Thread.: " + value);
                        flag = 0;
                        while( value < 55 && flag == 0);
                }
        }
    }
    
asked by anonymous 08.04.2014 / 00:35

1 answer

4

What is causing racing conditions in your code is the fact that access to variables is not atomic, that is, they are accessed concurrently by more than one thread . If you want these variables to be used by the code without the operation performed on one thread affects the operation performed by the other, you must encapsulate the operations of reading and changing the value of the variables in blocks synchronized (within which you can only enter one thread at a time) or use objects that guarantee the atomicity of the operation such as AtomicInteger .

    
08.04.2014 / 01:32