class Playground {
private static boolean running = true;
public static void main(String[] args) {
var t1 = new Thread(() -> {
while (running) {}
System.out.println("topjava.ru");
});
var t2 = new Thread(() -> {
running = false;
System.out.println("I love");
});
t1.start();
t2.start();
}
}
I love
topjava.ru
topjava.ru
I love
class Playground {
private static volatile boolean running = true;
...
}
L — локальная переменная: L1, L2
S — общая переменная: S1, S2. Видна нескольким потокам, может быть статической
S.X — S является ссылочной переменной, а X — полем объекта
1.2 — номер потока (1), номер строки (2)
1) 1.1, 2.1, 1.2, 2.2
2) 1.1, 2.1, 2.2, 1.2
3) 1.1, 2.1, 2.2
class Playground {
private static volatile int S1;
private static volatile int S2;
public static void main(String[] args) {
var t1 = new Thread(() -> {
int L1 = S1;
S2 = 2;
System.out.println("Thread1: " + L1);
});
var t2 = new Thread(() -> {
int L2 = S2;
S1 = 1;
System.out.println("Thread2: " + L2);
});
t1.start();
t2.start();
}
1) 1.1, 1.2, 1.3, 2.1, 2.2, 2.3
2) 2.1, 2.2, 2.3, 1.1, 1.2, 1.3
3) 1.1, 2.1, 1.2, 2.2, 1.3, 2.3
class SharedData {
volatile int X;
}
public class Playground {
static SharedData S1 = new SharedData();
static SharedData S2 = S1;
public static void main(String[] args) {
Thread thread1 = new Thread(() -> {
SharedData L1 = S1;
int L2 = L1.X;
SharedData L3 = S2;
int L4 = L3.X;
int L5 = L1.X;
System.out.println("Thread1: " + L2 + ", " + L4 + ", " + L5);
});
Thread thread2 = new Thread(() -> {
SharedData L6 = S1;
L6.X = 3;
System.out.println("Thread2: " + L6.X);
});
thread1.start();
thread2.start();
}
}