Версия 1:
package lab_3;
import java.util.concurrent.locks.*;
public class SynchronizedString {
private String value;
private ReadWriteLock lock;
public SynchronizedString() {
value = "";
lock = new ReentrantReadWriteLock();
}
public void write(String newValue) throws InterruptedException {
Lock writeLock = lock.writeLock();
writeLock.lock(); // Захват блокировки записи
try {
value = newValue;
} finally {
writeLock.unlock(); // Освобождение блокировки записи
}
}
public String read() throws InterruptedException {
//Lock readLock = lock.readLock();
//readLock.lock(); // Захват блокировки чтения
try {
return value;
} finally {
//readLock.unlock(); // Освобождение блокировки чтения
}
}
}
------
public static void main(String[] args) {
SynchronizedString synchronizedString = new SynchronizedString();
// Создание и запуск потоков-писателей
Thread writerThread1 = new Thread(() -> {
try {
synchronized (synchronizedString) {
synchronizedString.write("Hello");
System.out.println("Writer Thread 1: Successfully wrote 'Hello'");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread writerThread2 = new Thread(() -> {
try {
synchronized (synchronizedString) {
synchronizedString.write("World");
System.out.println("Writer Thread 2: Successfully wrote 'World'");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread writerThread3 = new Thread(() -> {
try {
synchronized (synchronizedString) {
synchronizedString.write("!!!");
System.out.println("Writer Thread 3: Successfully wrote '!!!'");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
// Создание и запуск потоков-читателей
Thread readerThread1 = new Thread(() -> {
try {
synchronized (synchronizedString) {
String value = synchronizedString.read();
System.out.println("Reader Thread 1: Read value: " + value);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread readerThread2 = new Thread(() -> {
try {
synchronized (synchronizedString) {
String value = synchronizedString.read();
System.out.println("Reader Thread 2: Read value: " + value);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread readerThread3 = new Thread(() -> {
try {
synchronized (synchronizedString) {
String value = synchronizedString.read();
System.out.println("Reader Thread 3: Read value: " + value);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
});
// Запуск потоков
writerThread1.start();
writerThread2.start();
writerThread3.start();
readerThread1.start();
readerThread2.start();
readerThread3.start();
}
