版权声明:Please make the source marked https://blog.csdn.net/qq_31807385/article/details/83998166
先看案例,如下
package hello_java;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ReadAndWrite {
public static void main(String[] args) {
ShareData04 shareData04 = new ShareData04();
new Thread(() -> {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
shareData04.write("juc....");
}).start();
for (int i = 0; i < 20; i++) {
new Thread(() -> {
shareData04.read();
}).start();
}
}
}
class ShareData04 {
private String content;
Lock lock = new ReentrantLock();
public String read() {
lock.lock();
try {
System.out.println("Student" + Thread.currentThread().getName() + "get = " + content);
return content;
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
return "";
}
public void write(String content) {
lock.lock();
try {
this.content = content;
System.out.println("The teacher write the content : " + content);
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
运行的结果,如下:
StudentThread-1get = null
StudentThread-4get = null
The teacher write the content : juc....
StudentThread-3get = juc....
StudentThread-2get = juc....
StudentThread-5get = juc....
StudentThread-7get = juc....
出现了,有的学生可以读到了数据,有的学生读不到数据的情况。正常的情况应该是,一旦老师修改了数据,所有的学生都应该可以看到数据。为什么会出现这样的现象呢?老师的线程先被启动,但是休眠了两毫秒,在这两毫秒,学生线程有若干被创建,并开始执行,两毫秒到了,老师插进来了,软件是不能这样设计的。
读的时候,不能写 即读写分离,写的时候;读和读可以并发,写和写也是互斥的。
解决该问题的方案如下:
package hello_java;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ReadAndWrite {
public static void main(String[] args) {
ShareData04 shareData04 = new ShareData04();
new Thread(() -> {
shareData04.write("juc....");
}).start();
for (int i = 0; i < 20; i++) {
new Thread(() -> {
shareData04.read();
}).start();
}
}
}
class ShareData04 {
private String content;
private ReadWriteLock lock = new ReentrantReadWriteLock();
public String read() {
lock.readLock().lock();
try {
System.out.println("Student" + Thread.currentThread().getName() + "get = " + content);
return content;
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.readLock().unlock();
}
return "";
}
public void write(String content) {
lock.writeLock().lock();
try {
this.content = content;
System.out.println("The teacher write the content : " + content);
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.writeLock().unlock();
}
}
}
运行结果如下:
The teacher write the content : juc....
StudentThread-1get = juc....
StudentThread-2get = juc....
StudentThread-4get = juc....
StudentThread-3get = juc....