Java Multithreading Learning and summarization (Iv.)

Source: Internet
Author: User
Tags semaphore

Signal Volume semaphore

Semaphore implementation of the function is similar to the toilet has 5 pits, if there are 10 people to the toilet, then at the same time only how many people to go to the toilet? At the same time only 5 people can occupy, when any one of the 5 people out of the way, one of the other 5 waiting for a person to occupy. The other 5 people who are waiting can be given a chance at random, or they can be given an opportunity in the order of first served, depending on the parameter options passed in when constructing the semaphore object. The semaphore object of a single semaphore can implement a mutex function, and it can be a thread that obtains a "lock", and another thread releases the "lock", which can be applied to some occasions of deadlock recovery.

                public void Run () {                    try {                        //Get License                        semp.acquire ();                        System.out.println ("Accessing:" + NO);                        Thread.Sleep ((Long) (Math.random () * 10000));                        After the visit, Release                        semp.release ();                        Availablepermits () refers to how many of the current beacon libraries can be used                        System.out.println ("-----------------" + semp.availablepermits ());                     } catch (Interruptedexception e) {                        e.printstacktrace ();                    }                }
About producers and consumers
    /**     * Warehouse for storing products *      * @author Lin Yi-chin     * @version 1.0 2013-7-24 PM 04:54:16 */public    class Storage {
   blockingqueue<product> queues = new linkedblockingqueue<product> (10);
The main use of this blocking queue to deal with production and consumption.
Signal variables
        Private lock lock = new Reentrantlock (); Account lock        Private Condition _save = Lock.newcondition ();//Deposit Conditions        Private Condition _draw = Lock.newcondition ();//Fetch Terms of payment
by _save.signalall ()
_save.await ();
In Java5, a lock can have multiple conditions, each of which can have multiple threads waiting, and by calling the await () method, you can let the thread wait under that condition. When you call the Signalall () method, you can also wake the waiting thread under that condition.
Basically, the lock is actually locked to condition.
   public void drawing (int x, String name) {            lock.lock ();//Get lock            try {                if (Cash-x < 0) {                    _draw.await (); Block withdrawal Operation                } else {                    cash-= x;//Withdrawal                    SYSTEM.OUT.PRINTLN (name + "withdrawal" + x + ", current balance is" + cash);                }                _save.signalall (); Wake up all deposit operations            } catch (Interruptedexception e) {                e.printstacktrace ();            } finally {                lock.unlock ();// Release lock            }        }
        public void saving (int x, String name) {            lock.lock ();//Get Lock            if (x > 0) {                cash + = x;//Deposit                SYSTEM.O UT.PRINTLN (name + "deposit" + x + ", current balance is" + cash);            }            _draw.signalall (); Wakes all waiting threads.            Lock.unlock ();//release Lock        }
You can see that lock does not cause a deadlock.
Obstacle Device

Countdownlatchu is the main thread that executes after all subroutines have been executed. The focus is on the main thread.
Cyclicbarrier is that there are more child threads that are executed to a certain point after the execution continues. The focus is on the child threads.

  Cyclicbarriertest test = new Cyclicbarriertest ();        Create the Maintask and set the task to be performed when all the fixed number of threads reach the barrier point (Runnable)        cyclicbarrier cb = new Cyclicbarrier (7, Test.new Maintask ( ));        Test.new SubTask ("A", CB). Start ();        Test.new SubTask ("B", CB). Start ();        Test.new SubTask ("C", CB). Start ();        Test.new SubTask ("D", CB). Start ();        Test.new SubTask ("E", CB). Start ();        Test.new SubTask ("F", CB). Start ();        Test.new SubTask ("G", CB). Start ();
is to have all the child threads execute to the
  Notice that the barrier has been completed                cb.await ();
The main thread is then executed.
Here is the execution to this point, and the first one is all done.
This can be used for sub-table queries.
That is, all the totals are calculated and then the main thread is executed.
It can also be done by way of join, Semaphore, atomic weight.
You can also determine the execution results of a child thread at timed intervals in the main thread. It can be learned by thread queues, variables, and so on.
can also, main thread await ();
Personally, it's more elegant to join.

Java Multithreading Learning and summarization (Iv.)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.