Технологии Java
Взаимодействие потоков
synchronized (o) { // Получение блокировки
…
} // Снятие блокировки
public synchronized int getValue() { … }
public int getValue() {
synchronized (this) { … }
}
class Example {
public static synchronized int getValue() { … }
… }
class Example {
public static int getValue() {
synchronized (Example.class) { … }
}
… }
class Queue<T> {
private E data;
public void set(E data) { … }
public E get() { … }
}
public void set(E data) {
while (true) { // Активное ожидание
synchronized (this) {
if (this.data == null) {
this.data = data;
break;
}
}
}
}
public E get() {
while (true) { // Активное ожидание
synchronized (this) {
if (data != null) {
E d = data;
data = null;
return d;
}
}
}
}
monitor.unlock() monitor.await() monitor.lock()
public synchronized void set(E data)
throws InterruptedException
{
while (this.data != null) {
wait(); // Пассивное ожидание
}
this.data = data;
notifyAll();
}
public synchronized E get()
throws InterruptedException {
while (data == null) {
wait(); // Пассивное ожидание
}
E d = data;
data = null;
notifyAll();
return d;
}
if (!queue.isEmpty()) {
// Fail
Object o = queue.poll();
}
int a = 0;
a = -1;
System.out.println(a);
long a = 0;
a = -1;
System.out.println(a);
int a = 0; int b = 0;
a = 10; b = 2;
System.out.println(a + b);
int a = 0;
a = 1; a = 2;
volatile List<String> list = null;
List<String> l = new ArrayList<>();
l.add("Hello");
list = l;
while (list == null) { }
return list.get(0);
public class Singleton {
public static volatile Singleton instance;
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
public void run() { // 0
synchronized (o1) { // 1
o1.notifyAll(); // 2
synchronized (o2) { // 3
try {
o2.wait(); // unlock 4, await 5, lock 6
} catch (InterruptedException e) {}
} // 7
} // 8
}
public await(Barrier that) { // 0
synchronized (this) { // 1
this.gen++; // 2
this.notify(); // 3
} // 4
synchronized (that) { // 5
while (this.gen > that.gen) { // 6
that.wait(); // unlock 7, await 8, lock 9
} // 10
} // 11
}