服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

java多线程设计模式详解之四

readwritelock

        多线程读写同一个对象的数据是很普遍的,通常,要避免读写冲突,必须保证任何时候仅有一个线程在写入,有线程正在读取的时候,写入操作就必须等待。简单说,就是要避免“写-写”冲突和“读-写”冲突。但是同时读是允许的,因为“读-读”不冲突,而且很安全。

       要实现以上的readwritelock,简单的使用synchronized就不行,我们必须自己设计一个readwritelock类,在读之前,必须先获得“读锁”,写之前,必须先获得“写锁”。举例说明:

datahandler对象保存了一个可读写的char[]数组:

package com.crackj2ee.thread;

public class datahandler {
    // store data:
    private char[] buffer = "aaaaaaaaaa".tochararray();

    private char[] doread() {
        char[] ret = new char[buffer.length];
        for(int i=0; i            ret[i] = buffer[i];
            sleep(3);
        }
        return ret;
    }

    private void dowrite(char[] data) {
        if(data!=null) {
            buffer = new char[data.length];
            for(int i=0; i                buffer[i] = data[i];
                sleep(10);
            }
        }
    }

    private void sleep(int ms) {
        try {
            thread.sleep(ms);
        }
        catch(interruptedexception ie) {}
    }
}

doread()和dowrite()方法是非线程安全的读写方法。为了演示,加入了sleep(),并设置读的速度大约是写的3倍,这符合通常的情况。

为了让多线程能安全读写,我们设计了一个readwritelock:

package com.crackj2ee.thread;
public class readwritelock {
    private int readingthreads = 0;
    private int writingthreads = 0;
    private int waitingthreads = 0; // waiting for write
    private boolean preferwrite = true;

    public synchronized void readlock() throws interruptedexception {
        while(writingthreads>0 || (preferwrite && waitingthreads>0))
            this.wait();
        readingthreads++;
    }

    public synchronized void readunlock() {
        readingthreads--;
        preferwrite = true;
        notifyall();
    }

    public synchronized void writelock() throws interruptedexception {
        waitingthreads++;
        try {
            while(readingthreads>0 || writingthreads>0)
                this.wait();
        }
        finally {
            waitingthreads--;
        }
        writingthreads++;
    }

    public synchronized void writeunlock() {
        writingthreads--;
        preferwrite = false;
        notifyall();
    }
}

readlock()用于获得读锁,readunlock()释放读锁,writelock()和writeunlock()一样。由于锁用完必须释放,因此,必须保证lock和unlock匹配。我们修改datahandler,加入readwritelock:

package com.crackj2ee.thread;
public class datahandler {
    // store data:
    private char[] buffer = "aaaaaaaaaa".tochararray();
    // lock:
    private readwritelock lock = new readwritelock();

    public char[] read(string name) throws interruptedexception {
        system.out.println(name + " waiting for read...");
        lock.readlock();
        try {
            char[] data = doread();
            system.out.println(name + " reads data: " + new string(data));
            return data;
        }
        finally {
            lock.readunlock();
        }
    }

    public void write(string name, char[] data) throws interruptedexception {
        system.out.println(name + " waiting for write...");
        lock.writelock();
        try {
            system.out.println(name + " wrote data: " + new string(data));
            dowrite(data);
        }
        finally {
            lock.writeunlock();
        }
    }

    private char[] doread() {
        char[] ret = new char[buffer.length];
        for(int i=0; i            ret[i] = buffer[i];
            sleep(3);
        }
        return ret;
    }
    private void dowrite(char[] data) {
        if(data!=null) {
            buffer = new char[data.length];
            for(int i=0; i                buffer[i] = data[i];
                sleep(10);
            }
        }
    }
    private void sleep(int ms) {
        try {
            thread.sleep(ms);
        }
        catch(interruptedexception ie) {}
    }
}

public方法read()和write()完全封装了底层的readwritelock,因此,多线程可以安全地调用这两个方法:

// readingthread不断读取数据:
package com.crackj2ee.thread;
public class readingthread extends thread {
    private datahandler handler;
    public readingthread(datahandler handler) {
        this.handler = handler;
    }
    public void run() {
        for(;;) {
            try {
                char[] data = handler.read(getname());
                thread.sleep((long)(math.random()*1000+100));
            }
            catch(interruptedexception ie) {
                break;
            }
        }
    }
}

// writingthread不断写入数据,每次写入的都是10个相同的字符:
package com.crackj2ee.thread;
public class writingthread extends thread {
    private datahandler handler;
    public writingthread(datahandler handler) {
        this.handler = handler;
    }
    public void run() {
        char[] data = new char[10];
        for(;;) {
            try {
                fill(data);
                handler.write(getname(), data);
                thread.sleep((long)(math.random()*1000+100));
            }
            catch(interruptedexception ie) {
                break;
            }
        }
    }
    // 产生一个a-z随机字符,填入char[10]:
    private void fill(char[] data) {
        char c = (char)(math.random()*26+'a');
        for(int i=0; i            data[i] = c;
    }
}

最后main负责启动这些线程:

package com.crackj2ee.thread;
public class main {
    public static void main(string[] args) {
        datahandler handler = new datahandler();
        thread[] ts = new thread[] {
                new readingthread(handler),
                new readingthread(handler),
                new readingthread(handler),
                new readingthread(handler),
                new readingthread(handler),
                new writingthread(handler),
                new writingthread(handler)
        };
        for(int i=0; i            ts[i].start();
        }
    }
}

我们启动了5个读线程和2个写线程,运行结果如下:

thread-0 waiting for read...
thread-1 waiting for read...
thread-2 waiting for read...
thread-3 waiting for read...
thread-4 waiting for read...
thread-5 waiting for write...
thread-6 waiting for write...
thread-4 reads data: aaaaaaaaaa
thread-3 reads data: aaaaaaaaaa
thread-2 reads data: aaaaaaaaaa
thread-1 reads data: aaaaaaaaaa
thread-0 reads data: aaaaaaaaaa
thread-5 wrote data: eeeeeeeeee
thread-6 wrote data: mmmmmmmmmm
thread-1 waiting for read...
thread-4 waiting for read...
thread-1 reads data: mmmmmmmmmm
thread-4 reads data: mmmmmmmmmm
thread-2 waiting for read...
thread-2 reads data: mmmmmmmmmm
thread-0 waiting for read...
thread-0 reads data: mmmmmmmmmm
thread-4 waiting for read...
thread-4 reads data: mmmmmmmmmm
thread-2 waiting for read...
thread-5 waiting for write...
thread-2 reads data: mmmmmmmmmm
thread-5 wrote data: gggggggggg
thread-6 waiting for write...
thread-6 wrote data: aaaaaaaaaa
thread-3 waiting for read...
thread-3 reads data: aaaaaaaaaa
......

可以看到,每次读/写都是完整的原子操作,因为我们每次写入的都是10个相同字符。并且,每次读出的都是最近一次写入的内容。

如果去掉readwritelock:

package com.crackj2ee.thread;
public class datahandler {

    // store data:
    private char[] buffer = "aaaaaaaaaa".tochararray();

    public char[] read(string name) throws interruptedexception {
        char[] data = doread();
        system.out.println(name + " reads data: " + new string(data));
        return data;
    }
    public void write(string name, char[] data) throws interruptedexception {
        system.out.println(name + " wrote data: " + new string(data));
        dowrite(data);
    }

    private char[] doread() {
        char[] ret = new char[10];
        for(int i=0; i<10; i++) {
            ret[i] = buffer[i];
            sleep(3);
        }
        return ret;
    }
    private void dowrite(char[] data) {
        for(int i=0; i<10; i++) {
            buffer[i] = data[i];
            sleep(10);
        }
    }
    private void sleep(int ms) {
        try {
            thread.sleep(ms);
        }
        catch(interruptedexception ie) {}
    }
}

运行结果如下:

thread-5 wrote data: aaaaaaaaaa
thread-6 wrote data: mmmmmmmmmm
thread-0 reads data: aaaaaaaaaa
thread-1 reads data: aaaaaaaaaa
thread-2 reads data: aaaaaaaaaa
thread-3 reads data: aaaaaaaaaa
thread-4 reads data: aaaaaaaaaa
thread-2 reads data: maaaaaaaaa
thread-3 reads data: maaaaaaaaa
thread-5 wrote data: cccccccccc
thread-1 reads data: maaaaaaaaa
thread-0 reads data: maaaaaaaaa
thread-4 reads data: maaaaaaaaa
thread-6 wrote data: eeeeeeeeee
thread-3 reads data: eeeeeccccc
thread-4 reads data: eeeeeeeeec
thread-1 reads data: eeeeeeeeee

可以看到在thread-6写入eeeeeeeeee的过程中,3个线程读取的内容是不同的。

思考

java的synchronized提供了最底层的物理锁,要在synchronized的基础上,实现自己的逻辑锁,就必须仔细设计readwritelock。

q: lock.readlock()为什么不放入try{ } 内?
a: 因为readlock()会抛出interruptedexception,导致readingthreads++不执行,而readunlock()在finally{ } 中,导致readingthreads--执行,从而使readingthread状态出错。writelock()也是类似的。

q: preferwrite有用吗?
a: 如果去掉preferwrite,线程安全不受影响。但是,如果读取线程很多,上一个线程还没有读取完,下一个线程又开始读了,就导致写入线程长时间无法获得writelock;如果写入线程等待的很多,一个接一个写,也会导致读取线程长时间无法获得readlock。preferwrite的作用是让读/写交替执行,避免由于读线程繁忙导致写无法进行和由于写线程繁忙导致读无法进行。

q: notifyall()换成notify()行不行?
a: 不可以。由于preferwrite的存在,如果一个线程刚读取完毕,此时preferwrite=true,再notify(),若恰好唤醒的是一个读线程,则while(writingthreads>0 || (preferwrite && waitingthreads>0))可能为true导致该读线程继续等待,而等待写入的线程也处于wait()中,结果所有线程都处于wait()状态,谁也无法唤醒谁。因此,notifyall()比notify()要来得安全。程序验证notify()带来的死锁:

thread-0 waiting for read...
thread-1 waiting for read...
thread-2 waiting for read...
thread-3 waiting for read...
thread-4 waiting for read...
thread-5 waiting for write...
thread-6 waiting for write...
thread-0 reads data: aaaaaaaaaa
thread-4 reads data: aaaaaaaaaa
thread-3 reads data: aaaaaaaaaa
thread-2 reads data: aaaaaaaaaa
thread-1 reads data: aaaaaaaaaa
thread-5 wrote data: cccccccccc
thread-2 waiting for read...
thread-1 waiting for read...
thread-3 waiting for read...
thread-0 waiting for read...
thread-4 waiting for read...
thread-6 wrote data: llllllllll
thread-5 waiting for write...
thread-6 waiting for write...
thread-2 reads data: llllllllll
thread-2 waiting for read...
(运行到此不动了)

注意到这种死锁是由于所有线程都在等待别的线程唤醒自己,结果都无法醒过来。这和两个线程希望获得对方已有的锁造成死锁不同。因此多线程设计的难度远远高于单线程应用。

扫描关注微信公众号