public class Playground {
private static boolean running;
public static void main(String[] args) {
var t1 = new Thread(() -> {
while (!running) {}
System.out.println("topjava.ru");
});
var t2 = new Thread(() -> {
running = true;
System.out.println("I love");
});
t1.start();
t2.start();
}
}
I love
topjava.ru
topjava.ru
I love
public class FoojayPlayground {
private static volatile boolean running;
...
}
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
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
4) 1.2, 2.1, 2.2, 1.1, 1.3, 2.3
Преимущества использования volatile:
public class BankAccount {
private long balance;
public BankAccount(long balance) {
this.balance = balance;
}
public void withdraw(long amount) {
long newBalance = balance - amount;
balance = newBalance;
}
public void deposit(long amount) {
long newBalance = balance + amount;
balance = newBalance;
}
@Override
public String toString() {
return String.valueOf(balance);
}
}
public class BankAccountTest {
public static void main(String[] args) throws InterruptedException {
BankAccount ba = new BankAccount(100);
var t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
ba.deposit(100);
}
});
var t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
ba.withdraw(100);
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(ba);
}
}
1) 1.1, 1.2, 2.1, 2.2
2) 2.1, 2.2, 1.1, 1.2
3) 1.1, 2.1, 2.2, 1.2
public class BankAccount {
private long balance;
private final Object lock = new Object();
public BankAccount(long balance) {
this.balance = balance;
}
public void withdraw(long amount) {
synchronized (lock) {
System.out.println("Acquired Lock: " + Thread.currentThread());
long newBalance = balance - amount;
balance = newBalance;
System.out.println("Unlocked the lock: " + Thread.currentThread());
}
}
public synchronized void deposit(long amount) {
synchronized (lock) {
System.out.println("Acquired Lock: " + Thread.currentThread());
long newBalance = balance + amount;
balance = newBalance;
System.out.println("Unlocked the lock: " + Thread.currentThread());
}
}
@Override
public String toString() {
return String.valueOf(balance);
}
}
public class Counter {
private int count;
public synchronized void increment() {
this.count = this.count + 1;
}
public int getCount() {
return count;
}
}