乐观锁

原理示例

  1. package com.thinking.in.java.course.chapter21;//: concurrency/FastSimulation.java
  2. import java.util.concurrent.TimeUnit;
  3. import java.util.concurrent.atomic.AtomicInteger;
  4. public class FastSimulation2 {
  5. static AtomicInteger ato = new AtomicInteger(10);
  6. public static void main(String[] args) throws Exception {
  7. new Thread(()->{
  8. int oldValue = ato.get();
  9. /* try {
  10. TimeUnit.MILLISECONDS.sleep(100);
  11. } catch (InterruptedException e) {
  12. e.printStackTrace();
  13. }*/
  14. System.out.println("原先获取的oldValue 为:"+oldValue+" 查看一下是否被其他线程修改了"+ato.get());
  15. int newValue = oldValue + 3;
  16. if(!ato.compareAndSet(oldValue,newValue)){
  17. System.out.println(Thread.currentThread().getName()+"记录被修改,已无法提交");
  18. }else{
  19. System.out.println(Thread.currentThread().getName()+"修改成功了 "+ato.get());
  20. }
  21. }).start();
  22. new Thread(()->{
  23. int oldValue = ato.get();
  24. int newValue = oldValue + 3;
  25. if(!ato.compareAndSet(oldValue,newValue)){
  26. System.out.println(Thread.currentThread().getName()+"修改提交失败");
  27. }else{
  28. System.out.println(Thread.currentThread().getName()+"修改成功了,并提交记录"+ato.get());
  29. }
  30. }).start();
  31. }
  32. }
  33. 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();

    }

}