Sunday 15 September 2013

java - Thread-safe multiple producer questions -


I am facing an interesting problem in real life. I made this problem simple here:

Two methods of design A () and a method B () Each method can be thought of producing an element atom (A or B). A chemical compound A [N] B [M] is required for N atom and M of atoms.

Before each of us, A and B () will block every call before N atom and M of atoms. When we reach A atoms and M of atoms, then first NA (call) and first MB () calls will return. For example, if I call N + 2A () and follow the call with the MB () call, then first NA (call) and all the mb (call) calls will be returned. 2A () calls being blocked?

How can I solve this problem? I am using Java

You : < Pre-> static class atma {} static class atom {} static class chemical compound {blocking qi and lt; ATMA & gt; Like = new link blocking queue & lt; ATMA & gt; (); BlockingQueue & LT; AtomB & gt; BS = new linked blockquote & lt; Atb & gt; (); Public Chemical Compound (int n, int nb) {while (na -! = 0) as.add (new ATA ()); While (NB -! = 0) B.Ed (new atb) } Public ATMA A () Interrupted Expressions throws {return.t.take (); } Public ATM (B) throws thrust; Option {return bs.take (); }} Public static zero chief (string [] args throws exceptions) {Last Chemical Compound CC = New Chemical Compound (2, 3); Thread Ta = New Thread (New Runnabel) {@ Override Public Wide Run} {While (true) {try {cc.A (); System.out.println ("AA Ho!"); Thread.sleep (100);} Grip (Interrupted Exception E) {e.printStackTrace ();}}}}); Ta.start (); Thread TB = new thread (new runnable) {@ Override Public Wide Run () {when (true) {try {cc.B}; System OutprintLN ("bb!"); Thread (100);} grip (interrupted e) e.printStackTrace ();}}}}); Tb.start (); Ta.join (); Tb.join (); Return; }

Thread is sleeping to display the possible interval of the thread, but definitely delete them in "production".

Result:

  got one! Got a b Got an A! Got a b Got a b    

No comments:

Post a Comment