Pessoal estudando sobre threads / volatile, entre outros detalhes, tentei implementar algo com volatile.
Pelo que entendi, quando você não precisa ter controle na gravação de uma variavel, ou seja, não precisa sincronizar a escrita e quer que os dados reflita em outra thread, então é utilizado volatile.
Conditions for correct use of volatilePorem quando fiz este teste, o valor que é alterado na thread de escrita, não é mostrado na thread de leitura, o que fiz de errado? Segue abaixo as classes.You can use volatile variables instead of locks only under a restricted set of circumstances. Both of the following criteria must be met for volatile variables to provide the desired thread-safety:
* Writes to the variable do not depend on its current value.
* The variable does not participate in invariants with other variables.
Fonte: http://www.ibm.com/developerworks/java/library/j-jtp06197.html
import java.util.Random;
public class Principal {
public volatile Integer count = 0;
public static void main(String[] args) {
Principal p = new Principal();
new Thread(new Escrita(p.count)).start();
new Thread(new Leitura(p.count)).start();
}
}
class Leitura implements Runnable {
private Integer count;
public Leitura(Integer count) {
this.count = count;
}
private void execute() throws InterruptedException {
while (true) {
System.out.println("Valor de count: " + count);
Thread.sleep(2000);
}
}
@Override
public void run() {
try {
execute();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Escrita implements Runnable {
private Integer count;
public Escrita(Integer count) {
this.count = count;
}
private void execute() throws InterruptedException {
Random r = new Random();
while (true) {
count = r.nextInt(1000);
System.out.println("Gravado: " + count);
Thread.sleep(3000);
}
}
@Override
public void run() {
try {
execute();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Att