공유 잠금(읽기 및 쓰기 잠금)
5202 단어 java 다중 루틴
문제 없음
코드는 다음과 같습니다.
package cn.link.lock;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class MyLock {
private volatile Map map = new HashMap<>();
private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
public void put(String key, Object value) {
// rwLock.writeLock().lock();
/*try {
}catch (Exception e){
}finally {
rwLock.writeLock().unlock();
}*/
System.out.println(Thread.currentThread().getName() + "\t :" + key);
try {
TimeUnit.MILLISECONDS.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
map.put(key, value);
System.out.println(Thread.currentThread().getName() + "\t :" + key);
}
public void get(String key) {
//rwLock.writeLock().lock();
/*try {
}catch (Exception e){
}finally {
rwLock.writeLock().unlock();
}*/
System.out.println(Thread.currentThread().getName() + "\t ");
try {
TimeUnit.MILLISECONDS.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Object value = map.get(key);
System.out.println(Thread.currentThread().getName() + "\t :" + value);
}
public static void main(String[] args) {
MyLock myLock = new MyLock();
for (int i = 1; i <= 5; i++) {
final int tempInt = i;
new Thread(new Runnable() {
@Override
public void run() {
myLock.put(tempInt + "", tempInt + "");
}
}, "" + i).start();
}
for (int i = 1; i <= 5; i++) {
final int tempInt = i;
new Thread(new Runnable() {
@Override
public void run() {
myLock.get(tempInt + "");
}
}, "" + i).start();
}
}
}
실행 결과는 다음과 같습니다.
1 쓰기 중: 1 2 쓰기 중: 2 3 쓰기 중: 3 4 쓰기 중: 4 5 쓰기 중: 5 1 읽기 2 읽기 3 읽기 4 읽기 5 읽기 3 쓰기 완료: 3 2 쓰기 완료: 2 쓰기 완료: 2 1 쓰기 완료: 1 4 쓰기 완료: 4 5 쓰기 완료: 5 1 읽기 완료: 5 1 읽기 완료:null 2 읽기 완료:null 4 읽기 완료픽업 완료: 4 3 읽기 완료: 3 5 읽기 완료: 5
쓰기 작업: 원자+독점(전체 과정은 완전한 통일이고 중간에 끊길 수 없음)
읽기와 쓰기 자물쇠를 달았다
package cn.link.lock;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class MyLock {
private volatile Map map = new HashMap<>();
private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
public void put(String key, Object value) {
try {
rwLock.writeLock().lock();
System.out.println(Thread.currentThread().getName() + "\t :" + key);
try {
TimeUnit.MILLISECONDS.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}catch (Exception e){
e.printStackTrace();
}finally {
rwLock.writeLock().unlock();
}
map.put(key, value);
System.out.println(Thread.currentThread().getName() + "\t :" + key);
}
public void get(String key) {
try {
rwLock.readLock().lock();
System.out.println(Thread.currentThread().getName() + "\t ");
try {
TimeUnit.MILLISECONDS.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Object value = map.get(key);
System.out.println(Thread.currentThread().getName() + "\t :" + value);
}catch (Exception e){
e.printStackTrace();
}finally {
rwLock.readLock().unlock();
}
}
public static void main(String[] args) {
MyLock myLock = new MyLock();
for (int i = 1; i <= 5; i++) {
final int tempInt = i;
new Thread(new Runnable() {
@Override
public void run() {
myLock.put(tempInt + "", tempInt + "");
}
}, "" + i).start();
}
for (int i = 1; i <= 5; i++) {
final int tempInt = i;
new Thread(new Runnable() {
@Override
public void run() {
myLock.get(tempInt + "");
}
}, "" + i).start();
}
}
}
실행 결과:
1 쓰기 완료: 1 쓰기 완료: 1 2 쓰기 완료: 2 쓰기 완료: 2 4 쓰기 완료: 4 4 쓰기 완료: 4 3 쓰기 완료: 3 3 쓰기 완료: 3 5 쓰기 완료: 5 5 쓰기 완료: 5 1 읽기 2 읽기 3 읽기 4 읽기 5 읽기 1 읽기 완료: 1 2 읽기 완료: 2 4 읽기 완료끝: 4 3 읽기 완료: 3 5 읽기 완료: 5
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
자바 기본 튜토리얼 양보 자바 다중 튜토리얼1. yield() 소개 yield()의 역할은 양보입니다.이것은 현재 스레드가'실행 상태'에서'준비 상태'로 들어가서 같은 우선순위를 가진 다른 대기 스레드가 실행권을 얻도록 할 수 있다.단, 현재 스레드가 yie...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.