乐观锁
原理示例
package com.thinking.in.java.course.chapter21;//: concurrency/FastSimulation.javaimport java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicInteger;public class FastSimulation2 {static AtomicInteger ato = new AtomicInteger(10);public static void main(String[] args) throws Exception {new Thread(()->{int oldValue = ato.get();/* try {TimeUnit.MILLISECONDS.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}*/System.out.println("原先获取的oldValue 为:"+oldValue+" 查看一下是否被其他线程修改了"+ato.get());int newValue = oldValue + 3;if(!ato.compareAndSet(oldValue,newValue)){System.out.println(Thread.currentThread().getName()+"记录被修改,已无法提交");}else{System.out.println(Thread.currentThread().getName()+"修改成功了 "+ato.get());}}).start();new Thread(()->{int oldValue = ato.get();int newValue = oldValue + 3;if(!ato.compareAndSet(oldValue,newValue)){System.out.println(Thread.currentThread().getName()+"修改提交失败");}else{System.out.println(Thread.currentThread().getName()+"修改成功了,并提交记录"+ato.get());}}).start();}}ReadWriteLock
ReadWriteLock
写锁须占得先机,所有读锁都将阻塞至写锁释放; 成对出现
示例
package com.thinking.in.java.course.chapter21;
import java.io.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public class ReaderWriterFile {
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock(true);
private volatile boolean flag = false;
private class WriterTask implements Runnable{
private String fileName;
private String content;
WriterTask(String fileName,String content){
this.fileName = fileName;
this.content=content;
}
@Override
public void run() {
Lock wlock = lock.writeLock();
wlock.lock();
try {
BufferedWriter writer = new BufferedWriter(
new FileWriter(new File(fileName), true));
writer.write(content);
TimeUnit.SECONDS.sleep(1);
writer.flush();
writer.close();
flag = true;
}catch (Exception e){
} finally {
wlock.unlock();
}
}
}
private class ReaderTask implements Runnable{
private String fileName;
ReaderTask(String fileName){
this.fileName = fileName;
}
@Override
public void run() {
while (!Thread.interrupted()) {
if(flag) {
Lock rlock = lock.readLock();
rlock.lock();
try {
BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));
String temp;
while ((temp = reader.readLine()) != null) {
System.out.println(temp);
}
flag=false;
break;
} catch (Exception e) {
} finally {
rlock.unlock();
}
}
}
}
}
public static void main(String[] args) throws InterruptedException {
final ReaderWriterFile readerWriterFile = new ReaderWriterFile();
WriterTask writerTask = readerWriterFile.new WriterTask("a", "helloabcdefghigklmn" +
"1111111111111111111111111" +
"2222222222222222222222222");
new Thread(writerTask).start();
final ReaderTask readerTask = readerWriterFile.new ReaderTask("a");
new Thread(readerTask).start();
new Thread(readerTask).start();
new Thread(readerTask).start();
}
}
