[BAEL-4213] Why are local variables thread safe
Added two small example for article about thread-safety for local variables.
This commit is contained in:
parent
5248012a8a
commit
da6ee4cc12
|
@ -0,0 +1,10 @@
|
|||
package com.baeldung.concurrent.localvariables;
|
||||
|
||||
public class LocalAndLambda {
|
||||
public static void main(String... args) {
|
||||
String text = "";
|
||||
// Un-commenting the next line will break compilation, because text is no longer effectively final
|
||||
// text = "675";
|
||||
new Thread(() -> System.out.println(text)).start();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
package com.baeldung.concurrent.localvariables;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
|
||||
public class LocalVariables implements Runnable {
|
||||
private int field;
|
||||
|
||||
public static void main(String... args) {
|
||||
LocalVariables target = new LocalVariables();
|
||||
new Thread(target).start();
|
||||
new Thread(target).start();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
field = new SecureRandom().nextInt();
|
||||
int local = new SecureRandom().nextInt();
|
||||
System.out.println(field + " - " + local);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue