服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Java实现生产者消费者问题与读者写者问题详解

Java实现生产者消费者问题与读者写者问题详解

2021-02-02 11:54Hosee Java教程

这篇文章主要介绍了Java实现生产者消费者问题与读者写者问题详解,小编觉得挺不错的,这里分享给大家,供需要的亲朋好友参考。

1、生产者消费者问题

Java实现生产者消费者问题与读者写者问题详解

生产者消费者问题是研究多线程程序时绕不开的经典问题之一,它描述是有一块缓冲区作为仓库,生产者可以将产品放入仓库,消费者则可以从仓库中取走产品。解决生产者/消费者问题的方法可分为两类:(1)采用某种机制保护生产者和消费者之间的同步;(2)在生产者和消费者之间建立一个管道。第一种方式有较高的效率,并且易于实现,代码的可控制性较好,属于常用的模式。第二种管道缓冲区不易控制,被传输数据对象不易于封装等,实用性不强。

同步问题核心在于:如何保证同一资源被多个线程并发访问时的完整性。常用的同步方法是采用信号或加锁机制,保证资源在任意时刻至多被一个线程访问。java语言在多线程编程上实现了完全对象化,提供了对同步机制的良好支持。在java中一共有五种方法支持同步,其中前四个是同步方法,一个是管道方法。

wait() / notify()方法
await() / signal()方法
blockingqueue阻塞队列方法
semaphore方法
pipedinputstream / pipedoutputstream

1.1 wait() / notify()方法

wait() / nofity()方法是基类object的两个方法,也就意味着所有java类都会拥有这两个方法,这样,我们就可以为任何对象实现同步机制。

wait()方法:当缓冲区已满/空时,生产者/消费者线程停止自己的执行,放弃锁,使自己处于等等状态,让其他线程执行。

notify()方法:当生产者/消费者向缓冲区放入/取出一个产品时,向其他等待的线程发出可执行的通知,同时放弃锁,使自己处于等待状态。

各起了4个生产者,4个消费者

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package test;
public class hosee {
    private static integer count = 0;
    private final integer full = 10;
    private static string lock = "lock";
    class producer implements runnable {
        @override public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    thread.sleep(3000);
                }
                catch (exception e) {
                    e.printstacktrace();
                }
                synchronized (lock) {
                    while (count == full) {
                        try {
                            lock.wait();
                        }
                        catch (exception e) {
                            e.printstacktrace();
                        }
                    }
                    count++;
                    system.out.println(thread.currentthread().getname() + "生产者生产,目前总共有" + count);
                    lock.notifyall();
                }
            }
        }
    }
    class consumer implements runnable {
        @override public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    thread.sleep(3000);
                }
                catch (interruptedexception e1) {
                    e1.printstacktrace();
                }
                synchronized (lock) {
                    while (count == 0) {
                        try {
                            lock.wait();
                        }
                        catch (exception e) {
                            todo: handle exception e.printstacktrace();
                        }
                    }
                    count--;
                    system.out.println(thread.currentthread().getname() + "消费者消费,目前总共有" + count);
                    lock.notifyall();
                }
            }
        }
    }
    public static void main(string[] args) throws exception {
        hosee hosee = new hosee();
        new thread(hosee.new producer()).start();
        new thread(hosee.new consumer()).start();
        new thread(hosee.new producer()).start();
        new thread(hosee.new consumer()).start();
        new thread(hosee.new producer()).start();
        new thread(hosee.new consumer()).start();
        new thread(hosee.new producer()).start();
        new thread(hosee.new consumer()).start();
    }
}

(需要注意的是,用什么加锁就用什么notify和wait,实例中使用的是lock)

部分打印结果:

Java实现生产者消费者问题与读者写者问题详解

由于生产者和消费者说明一致,所以最多都是在2左右,当减少一个消费者时,则会加到10。

1.2 await() / signal()方法

首先,我们先来看看await()/signal()与wait()/notify()的区别:

wait()和notify()必须在synchronized的代码块中使用 因为只有在获取当前对象的锁时才能进行这两个操作 否则会报异常 而await()和signal()一般与lock()配合使用。
wait是object的方法,而await只有部分类有,如condition。
await()/signal()和新引入的锁定机制lock直接挂钩,具有更大的灵活性。
那么为什么有了synchronized还要提出lock呢?

1.2.1 对synchronized的改进

synchronized并不完美,它有一些功能性的限制 —— 它无法中断一个正在等候获得锁的线程,也无法通过投票得到锁,如果不想等下去,也就没法得到锁。同步还要求锁的释放只能在与获得锁所在的堆栈帧相同的堆栈帧中进行,多数情况下,这没问题(而且与异常处理交互得很好),但是,确实存在一些非块结构的锁定更合适的情况。

1.2.2 reentrantlock 类

java.util.concurrent.lock 中的 lock 框架是锁定的一个抽象,它允许把锁定的实现作为 java 类,而不是作为语言的特性来实现(更加面向对象)。这就为 lock 的多种实现留下了空间,各种实现可能有不同的调度算法、性能特性或者锁定语义。 reentrantlock 类实现了 lock ,它拥有与 synchronized 相同的并发性和内存语义,但是添加了类似锁投票、定时锁等候和可中断锁等候的一些特性。此外,它还提供了在激烈争用情况下更佳的性能。(换句话说,当许多线程都想访问共享资源时,jvm 可以花更少的时候来调度线程,把更多时间用在执行线程上。)

reentrant 锁意味着什么呢?简单来说,它有一个与锁相关的获取计数器,如果拥有锁的某个线程再次得到锁,那么获取计数器就加1,然后锁需要被释放两次才能获得真正释放(重入锁)。这模仿了 synchronized 的语义;如果线程进入由线程已经拥有的监控器保护的 synchronized 块,就允许线程继续进行,当线程退出第二个(或者后续) synchronized 块的时候,不释放锁,只有线程退出它进入的监控器保护的第一个synchronized 块时,才释放锁。

简单解释下重入锁:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class child extends father implements runnable{
    final static child child = new child();//为了保证锁唯一
    public static void main(string[] args) {
        for (int i = 0; i < 50; i++) {
            new thread(child).start();
        }
    }
    public synchronized void dosomething() {
        system.out.println("1child.dosomething()");
        doanotherthing(); // 调用自己类中其他的synchronized方法
    }
    private synchronized void doanotherthing() {
        super.dosomething(); // 调用父类的synchronized方法
        system.out.println("3child.doanotherthing()");
    }
    @override
    public void run() {
        child.dosomething();
    }
}
class father {
    public synchronized void dosomething() {
        system.out.println("2father.dosomething()");
    }
}

上述代码的锁都是child对象,当执行child.dosomething时,该线程获得child对象的锁,在dosomething方法内执行doanotherthing时再次请求child对象的锁,因为synchronized是重入锁,所以可以得到该锁,继续在doanotherthing里执行父类的dosomething方法时第三次请求child对象的锁,同理可得到,如果不是重入锁的话,那这后面这两次请求锁将会被一直阻塞,从而导致死锁。

在查看下面代码示例时,可以看到 lock 和 synchronized 有一点明显的区别 —— lock 必须在 finally 块中释放。否则,如果受保护的代码将抛出异常,锁就有可能永远得不到释放!这一点区别看起来可能没什么,但是实际上,它极为重要。忘记在 finally 块中释放锁,可能会在程序中留下一个定时炸弹,当有一天炸弹爆炸时,您要花费很大力气才有找到源头在哪。而使用同步,jvm 将确保锁会获得自动释放。

?
1
2
3
4
5
6
7
8
lock lock = new reentrantlock();
lock.lock();
try {
 // update object state
}
finally {
 lock.unlock();
}

除此之外,与目前的 synchronized 实现相比,争用下的 reentrantlock 实现更具可伸缩性。(在未来的 jvm 版本中,synchronized 的争用性能很有可能会获得提高。)这意味着当许多线程都在争用同一个锁时,使用 reentrantlock 的总体开支通常要比 synchronized 少得多。

1.2.3 什么时候选择用 reentrantlock 代替 synchronized

在 java1.5 中,synchronized 是性能低效的。因为这是一个重量级操作,需要调用操作接口,导致有可能加锁消耗的系统时间比加锁以外的操作还多。相比之下使用 java 提供的 lock 对象,性能更高一些。但是到了 java1.6,发生了变化。synchronized 在语义上很清晰,可以进行很多优化,有适应自旋,锁消除,锁粗化,轻量级锁,偏向锁等等。导致在 java1.6 上 synchronized 的性能并不比 lock 差。官方也表示,他们也更支持 synchronized,在未来的版本中还有优化余地。

所以在确实需要一些 synchronized 所没有的特性的时候,比如时间锁等候、可中断锁等候、无块结构锁、多个条件变量或者锁投票使用reentrantlock。reentrantlock 还具有可伸缩性的好处,应当在高度争用的情况下使用它,但是请记住,大多数 synchronized 块几乎从来没有出现过争用,所以可以把高度争用放在一边。我建议用 synchronized 开发,直到确实证明 synchronized 不合适,而不要仅仅是假设如果使用 reentrantlock “性能会更好”。请记住,这些是供高级用户使用的高级工具。(而且,真正的高级用户喜欢选择能够找到的最简单工具,直到他们认为简单的工具不适用为止。)。一如既往,首先要把事情做好,然后再考虑是不是有必要做得更快。

1.2.4 接下来我们使用reentrantlock来实现生产者消费者问题

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package test;
import java.util.concurrent.locks.condition;
import java.util.concurrent.locks.lock;
import java.util.concurrent.locks.reentrantlock;
public class hosee {
    private static integer count = 0;
    private final integer full = 10;
    final lock lock = new reentrantlock();
    final condition notfull = lock.newcondition();
    final condition notempty = lock.newcondition();
    class producer implements runnable {
        @override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    thread.sleep(3000);
                } catch (exception e) {
                    e.printstacktrace();
                }
                lock.lock();
                try {
                    while (count == full) {
                        try {
                            notfull.await();
                        } catch (interruptedexception e) {
                            // todo auto-generated catch block
                            e.printstacktrace();
                        }
                    }
                    count++;
                    system.out.println(thread.currentthread().getname()
                            + "生产者生产,目前总共有" + count);
                    notempty.signal();
                } finally {
                    lock.unlock();
                }
            }
        }
    }
    class consumer implements runnable {
        @override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    thread.sleep(3000);
                } catch (interruptedexception e1) {
                    e1.printstacktrace();
                }
                lock.lock();
                try {
                    while (count == 0) {
                        try {
                            notempty.await();
                        } catch (exception e) {
                            // todo: handle exception
                            e.printstacktrace();
                        }
                    }
                    count--;
                    system.out.println(thread.currentthread().getname()
                            + "消费者消费,目前总共有" + count);
                    notfull.signal();
                } finally {
                    lock.unlock();
                }
            }
        }
    }
    public static void main(string[] args) throws exception {
        hosee hosee = new hosee();
        new thread(hosee.new producer()).start();
        new thread(hosee.new consumer()).start();
        new thread(hosee.new producer()).start();
        new thread(hosee.new consumer()).start();
        new thread(hosee.new producer()).start();
        new thread(hosee.new consumer()).start();
        new thread(hosee.new producer()).start();
        new thread(hosee.new consumer()).start();
    }
}

运行结果与第一个类似。上述代码用了两个condition,其实用一个也是可以的,只不过要signalall()。

1.3 blockingqueue阻塞队列方法

blockingqueue是jdk5.0的新增内容,它是一个已经在内部实现了同步的队列,实现方式采用的是我们第2种await() / signal()方法。它可以在生成对象时指定容量大小。它用于阻塞操作的是put()和take()方法。

put()方法:类似于我们上面的生产者线程,容量达到最大时,自动阻塞。

take()方法:类似于我们上面的消费者线程,容量为0时,自动阻塞。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package test;
import java.util.concurrent.arrayblockingqueue;
import java.util.concurrent.blockingqueue;
public class hosee {
    private static integer count = 0;
    final blockingqueue<integer> bq = new arrayblockingqueue<integer>(10);
    class producer implements runnable {
        @override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    thread.sleep(3000);
                } catch (exception e) {
                    e.printstacktrace();
                }
                try {
                    bq.put(1);
                    count++;
                    system.out.println(thread.currentthread().getname()
                            + "生产者生产,目前总共有" + count);
                } catch (interruptedexception e) {
                    // todo auto-generated catch block
                    e.printstacktrace();
                }
            }
        }
    }
    class consumer implements runnable {
        @override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    thread.sleep(3000);
                } catch (interruptedexception e1) {
                    e1.printstacktrace();
                }
                try {
                    bq.take();
                    count--;
                    system.out.println(thread.currentthread().getname()
                            + "消费者消费,目前总共有" + count);
                } catch (exception e) {
                    // todo: handle exception
                    e.printstacktrace();
                }
            }
        }
    }
    public static void main(string[] args) throws exception {
        hosee hosee = new hosee();
        new thread(hosee.new producer()).start();
        new thread(hosee.new consumer()).start();
        new thread(hosee.new producer()).start();
        new thread(hosee.new consumer()).start();
        new thread(hosee.new producer()).start();
        new thread(hosee.new consumer()).start();
        new thread(hosee.new producer()).start();
        new thread(hosee.new consumer()).start();
    }
}

其实这个blockingqueue比较难用代码来演示,因为put()与take()方法无法与输出语句保证同步,当然你可以自己去实现 blockingqueue(blockingqueue是用await()/signal() 实现的)。所以在输出结果上你会发现不匹配。

例如:当缓冲区已满,生产者在put()操作时,put()内部调用了await()方法,放弃了线程的执行,然后消费者线程执行,调用take()方法,take()内部调用了signal()方法,通知生产者线程可以执行,致使在消费者的println()还没运行的情况下生产者的println()先被执行,所以有了输出不匹配的情况。

对于blockingqueue大家可以放心使用,这可不是它的问题,只是在它和别的对象之间的同步有问题。

1.4 semaphore方法

semaphore 信号量,就是一个允许实现设置好的令牌。也许有1个,也许有10个或更多。
谁拿到令牌(acquire)就可以去执行了,如果没有令牌则需要等待。
执行完毕,一定要归还(release)令牌,否则令牌会被很快用光,别的线程就无法获得令牌而执行下去了。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package test;
import java.util.concurrent.semaphore;
public class hosee
{
    int count = 0;
    final semaphore notfull = new semaphore(10);
    final semaphore notempty = new semaphore(0);
    final semaphore mutex = new semaphore(1);
    class producer implements runnable
    {
        @override
        public void run()
        {
            for (int i = 0; i < 10; i++)
            {
                try
                {
                    thread.sleep(3000);
                }
                catch (exception e)
                {
                    e.printstacktrace();
                }
                try
                {
                    notfull.acquire();//顺序不能颠倒,否则会造成死锁。
                    mutex.acquire();
                    count++;
                    system.out.println(thread.currentthread().getname()
                            + "生产者生产,目前总共有" + count);
                }
                catch (exception e)
                {
                    e.printstacktrace();
                }
                finally
                {
                    mutex.release();
                    notempty.release();
                }
            }
        }
    }
    class consumer implements runnable
    {
        @override
        public void run()
        {
            for (int i = 0; i < 10; i++)
            {
                try
                {
                    thread.sleep(3000);
                }
                catch (interruptedexception e1)
                {
                    e1.printstacktrace();
                }
                try
                {
                    notempty.acquire();//顺序不能颠倒,否则会造成死锁。
                    mutex.acquire();
                    count--;
                    system.out.println(thread.currentthread().getname()
                            + "消费者消费,目前总共有" + count);
                }
                catch (exception e)
                {
                    e.printstacktrace();
                }
                finally
                {
                    mutex.release();
                    notfull.release();
                }
            }
        }
    }
    public static void main(string[] args) throws exception
    {
        hosee hosee = new hosee();
        new thread(hosee.new producer()).start();
        new thread(hosee.new consumer()).start();
        new thread(hosee.new producer()).start();
        new thread(hosee.new consumer()).start();
        new thread(hosee.new producer()).start();
        new thread(hosee.new consumer()).start();
        new thread(hosee.new producer()).start();
        new thread(hosee.new consumer()).start();
    }
}

注意notfull.acquire()与mutex.acquire()的位置不能互换,如果先得到互斥锁再发生等待,会造成死锁。

1.5 pipedinputstream / pipedoutputstream

这个类位于java.io包中,是解决同步问题的最简单的办法,一个线程将数据写入管道,另一个线程从管道读取数据,这样便构成了一种生产者/消费者的缓冲区编程模式。pipedinputstream/pipedoutputstream只能用于多线程模式,用于单线程下可能会引发死锁。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package test;
import java.io.ioexception;
import java.io.pipedinputstream;
import java.io.pipedoutputstream;
public class hosee {
    final pipedinputstream pis = new pipedinputstream();
    final pipedoutputstream pos = new pipedoutputstream();
    {
        try {
            pis.connect(pos);
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }
    class producer implements runnable {
        @override
        public void run() {
            try{
        while(true){
          int b = (int) (math.random() * 255);
          system.out.println("producer: a byte, the value is " + b);
          pos.write(b);
          pos.flush();
        }
      }catch(exception e){
        e.printstacktrace();
      }finally{
        try{
          pos.close();
          pis.close();
        }catch(ioexception e){
          system.out.println(e);
        }
      }
        }
    }
    class consumer implements runnable {
        @override
        public void run() {
            try{
        while(true){
          int b = pis.read();
          system.out.println("consumer: a byte, the value is " + string.valueof(b));
        }
      }catch(exception e){
        e.printstacktrace();
      }finally{
        try{
          pos.close();
          pis.close();
        }catch(ioexception e){
          system.out.println(e);
        }
      }
        }
    }
    public static void main(string[] args) throws exception {
        hosee hosee = new hosee();
        new thread(hosee.new producer()).start();
        new thread(hosee.new consumer()).start();
    }
}

与阻塞队列一样,由于read()/write()方法与输出方法不一定同步,输出结果方面会发生不匹配现象,为了使结果更加明显,这里只有1个消费者和1个生产者。

2、读者写者问题

读者—写者问题(readers-writers problem)也是一个经典的并发程序设计问题,是经常出现的一种同步问题。计算机系统中的数据(文件、记录)常被多个进程共享,但其中某些进程可能只要求读数据(称为读者reader);另一些进程则要求修改数据(称为写者writer)。就共享数据而言,reader和writer是两组并发进程共享一组数据区,要求:

(1)允许多个读者同时执行读操作;

(2)不允许读者、写者同时操作;

(3)不允许多个写者同时操作。

reader和writer的同步问题分为读者优先、弱写者优先(公平竞争)和强写者优先三种情况,它们的处理方式不同。

首先我们都只考虑公平竞争的情况下,看看java有哪些方法可以实现读者写者问题

2.1 读写锁

reentrantreadwritelock会使用两把锁来解决问题,一个读锁,一个写锁
线程进入读锁的前提条件:
没有其他线程的写锁,
没有写请求或者有写请求,但调用线程和持有锁的线程是同一个
线程进入写锁的前提条件:
没有其他线程的读锁
没有其他线程的写锁

到reentrantreadwritelock,首先要做的是与reentrantlock划清界限。它和后者都是单独的实现,彼此之间没有继承或实现的关系。然后就是总结这个锁机制的特性了:

重入(在上文reentrantlock处已经介绍了)方面其内部的writelock可以获取readlock,但是反过来readlock想要获得writelock则永远都不要想。

writelock可以降级为readlock,顺序是:先获得writelock再获得readlock,然后释放writelock,这时候线程将保持readlock的持有。反过来readlock想要升级为writelock则不可能,为什么?参看(1),呵呵.

readlock可以被多个线程持有并且在作用时排斥任何的writelock,而writelock则是完全的互斥。这一特性最为重要,因为对于高读取频率而相对较低写入的数据结构,使用此类锁同步机制则可以提高并发量。

不管是readlock还是writelock都支持interrupt,语义与reentrantlock一致。

writelock支持condition并且与reentrantlock语义一致,而readlock则不能使用condition,否则抛出unsupportedoperationexception异常。

看下reentrantreadwritelock这个类的两个构造函数

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public reentrantreadwritelock() {
    this(false);
  }
  /**
   * creates a new {@code reentrantreadwritelock} with
   * the given fairness policy.
   *
   * @param fair {@code true} if this lock should use a fair ordering policy
   */
  public reentrantreadwritelock(boolean fair) {
    sync = (fair)? new fairsync() : new nonfairsync();
    readerlock = new readlock(this);
    writerlock = new writelock(this);
  }

fair这个参数表示是否是创建一个公平的读写锁,还是非公平的读写锁。也就是抢占式还是非抢占式

公平和非公平:公平表示获取的锁的顺序是按照线程加锁的顺序来分配获取到锁的线程时最先加锁的线程,是按照fifo的顺序来分配锁的;非公平表示获取锁的顺序是无需的,后来加锁的线程可能先获得锁,这种情况就导致某些线程可能一直没获取到锁。

公平锁为啥会影响性能,从code上来看看公平锁仅仅是多了一项检查是否在队首会影响性能,如不是,那么又是在什么地方影响的?假如是闯入的线程,会排在队尾并睡觉(parking)等待前任节点唤醒,这样势必会比非公平锁添加很多paking和unparking的操作

一般的应用场景是: 如果有多个读线程,一个写线程,而且写线程在操作的时候需要阻塞读线程,那么此时就需要使用公平锁,要不然可能写线程一直获取不到锁,导致线程饿死。

再简单说下锁降级

重入还允许从写入锁降级为读取锁,其实现方式是:先获取写入锁,然后获取读取锁,最后释放写入锁。但是,从读取锁升级到写入锁是不可能的。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
rwl.readlock().lock();
   if (!cachevalid) {
     // must release read lock before acquiring write lock
     rwl.readlock().unlock();
     rwl.writelock().lock();
    
     if (!cachevalid) {
      data = ...
      cachevalid = true;
     }
    
     rwl.readlock().lock();
     rwl.writelock().unlock(); // 降级:先获取读锁再释放写锁
   }

下面我们用读写锁来实现读者写者问题

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.util.random;
import java.util.concurrent.locks.reentrantreadwritelock;
public class readwritelocktest {
    public static void main(string[] args) {
        final queue3 q3 = new queue3();
        for (int i = 0; i < 3; i++) {
            new thread() {
                public void run() {
                    while (true) {
                        q3.get();
                    }
                }
            }.start();
        }
        for (int i = 0; i < 3; i++) {
            new thread() {
                public void run() {
                    while (true) {
                        q3.put(new random().nextint(10000));
                    }
                }
            }.start();
        }
    }
}
class queue3 {
    private object data = null;// 共享数据,只能有一个线程能写该数据,但可以有多个线程同时读该数据。
    private reentrantreadwritelock rwl = new reentrantreadwritelock();
    public void get() {
        rwl.readlock().lock();// 上读锁,其他线程只能读不能写
        system.out.println(thread.currentthread().getname()
                + " be ready to read data!");
        try {
            thread.sleep((long) (math.random() * 1000));
        } catch (interruptedexception e) {
            e.printstacktrace();
        }
        system.out.println(thread.currentthread().getname()
                + "have read data :" + data);
        rwl.readlock().unlock(); // 释放读锁,最好放在finnaly里面
    }
    public void put(object data) {
        rwl.writelock().lock();// 上写锁,不允许其他线程读也不允许写
        system.out.println(thread.currentthread().getname()
                + " be ready to write data!");
        try {
            thread.sleep((long) (math.random() * 1000));
        } catch (interruptedexception e) {
            e.printstacktrace();
        }
        this.data = data;
        system.out.println(thread.currentthread().getname()
                + " have write data: " + data);
        rwl.writelock().unlock();// 释放写锁
    }
}

运行结果:

?
1
2
3
4
5
6
7
8
9
10
11
12
thread-0 be ready to read data!
thread-1 be ready to read data!
thread-2 be ready to read data!
thread-0have read data :null
thread-2have read data :null
thread-1have read data :null
thread-5 be ready to write data!
thread-5 have write data: 6934
thread-5 be ready to write data!
thread-5 have write data: 8987
thread-5 be ready to write data!
thread-5 have write data: 8496

2.2 semaphore信号量

在1.4中已经介绍了用信号量来实现生产者消费者问题,现在我们将用信号量来实现读者写者问题,信号量的相关知识不再重复,直接看代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package test;
import java.util.random;
import java.util.concurrent.semaphore;
public class readwrite
{
    public static void main(string[] args)
    {
        final queue3 q3 = new queue3();
        for (int i = 0; i < 3; i++)
        {
            new thread()
            {
                public void run()
                {
                    while (true)
                    {
                        try
                        {
                            thread.sleep((long) (math.random() * 1000));
                        }
                        catch (interruptedexception e)
                        {
                            e.printstacktrace();
                        }
                        q3.get();
                    }
                }
            }.start();
        }
        for (int i = 0; i < 3; i++)
        {
            new thread()
            {
                public void run()
                {
                    while (true)
                    {
                        try
                        {
                            thread.sleep((long) (math.random() * 1000));
                        }
                        catch (interruptedexception e)
                        {
                            e.printstacktrace();
                        }
                        q3.put(new random().nextint(10000));
                    }
                }
            }.start();
        }
    }
}
class queue3
{
    private object data = null;// 共享数据,只能有一个线程能写该数据,但可以有多个线程同时读该数据。
    private semaphore wmutex = new semaphore(1);
    private semaphore rmutex = new semaphore(2);
    private int count = 0;
    public void get()
    {
        try
        {
            rmutex.acquire();
            if (count == 0)
                wmutex.acquire();// 当第一读进程欲读数据库时,阻止写进程写
            count++;
            system.out.println(thread.currentthread().getname()
                    + " be ready to read data!");
            try
            {
                thread.sleep((long) (math.random() * 1000));
            }
            catch (interruptedexception e)
            {
                e.printstacktrace();
            }
            system.out.println(thread.currentthread().getname()
                    + "have read data :" + data);
            count--;
            if (count == 0)
                wmutex.release();
            rmutex.release();
        }
        catch (exception e)
        {
            e.printstacktrace();
        }
    }
    public void put(object data)
    {
        try
        {
            wmutex.acquire();
            system.out.println(thread.currentthread().getname()
                    + " be ready to write data!");
            try
            {
                thread.sleep((long) (math.random() * 1000));
            }
            catch (interruptedexception e)
            {
                e.printstacktrace();
            }
            this.data = data;
            system.out.println(thread.currentthread().getname()
                    + " have write data: " + data);
        }
        catch (exception e)
        {
            e.printstacktrace();
        }
        finally
        {
            wmutex.release();
        }
    }
}

单纯使用信号量不能解决读者与写者问题,必须引入计数器count(可以用countdownlatch代替 )对读进程计数; count与wmutex结合使用,使读读能同时进行,读写排斥。count为0时表示读进程开始,此时写进程阻塞(wmutex被读进程获取),当count不为0时,表示有多个读进程,就不用操作 wmutex了,因为第一个读进程已经获得了 wmutex。count表示有多少个读进程在读,每次有一个就+1,读完了-1,当count==0时,表示读进程都结束了。此时 wmutex释放,写进程才有机会获得wmutex。为了使读进程不要一直占有 wmutex,最好让读进程sleep一下,让写进程有机会获得wmutex,使效果更明显。

总结:

以上就是本文关于java实现生产者消费者问题与读者写者问题详解的全部内容,希望对大家有所帮助。有什么问题可以随时留言,小编会及时回复大家的。感谢朋友们对本站的支持!

原文链接:https://my.oschina.net/hosee/blog/485121

延伸 · 阅读

精彩推荐