[Java Concurrent] A simple case of concurrent access to shared resources

Source: Internet
Author: User

Evengenerator is an even-numbered generator, and each call to next () adds 2 and returns the result after the overlay. In this case, it acts as a shared resource.

The Evenchecker implements the Runnable interface, which enables a new thread to execute the run () task to detect whether the even-numbered generator pointed to returns even values each time.

Evencheckerthreaddemo is used to demonstrate execution under multi-threading.

Non-linear security version

Evengenerator, even generators, each call to a next () will add 2 and return the result after the overlay.

The next () method here is non-linear and safe, and may return odd numbers when the threads are accessed concurrently. Once a thread executes the first additive statement, it is interrupted by the scheduler, the replacement context, and another process starts executing the next () method, which returns an odd number.

 Public class evengenerator {        privateint count = 0;      Public int Next () {        count+ +;        Count++        ; return count;    }}

The Evenchecker detects whether the Evengenerator is returning an even number each time.

 Public classEvencheckerImplementsRunnable {Privateevengenerator eg; Private Final intid = count++; Private Static intCount = 0; @Override Public voidrun () { while(true){            intres =Eg.next (); if(res% 2! = 0) {System.out.println ("Not even" + res + "| Thread # "+ID);  Break; }        }    }         Publicevenchecker (Evengenerator eg) { This. eg =eg; }}

Demonstrates execution under multi-threading, with multiple threads executing evenchecker at the same time, but referencing the same evengenerator

ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors; Public classEvencheckerthreaddemo { Public Static voidMain () {Executorservice exec=Executors.newcachedthreadpool (); Evengenerator eg=NewEvengenerator ();  for(inti = 0; i< 5; i++) {Exec.execute (Newevenchecker (eg)); }    }}

Linear Security Version 1

Use the Synchronized keyword to make the next () method thread-safe, ensuring that at most one thread at a time, at most, the method is entered.

 Public class evengenerator {        privateint count = 0;              Public synchronized int Next () {        count+ +;        Count++        ; return count;    }}
Linear Security Version 2

Use Lock to synchronize statements that access and modify shared variables to ensure that at most one thread enters the block code at the same time. Using the try-finally structure, you can ensure that Lock must be released.

ImportJava.util.concurrent.locks.Lock;ImportJava.util.concurrent.locks.ReentrantLock; Public classEvengenerator {Private intCount = 0; PrivateLock lock =NewReentrantlock ();  Public intNext () {Lock.lock (); Try{Count++; Count++; returncount; } finally{lock.unlock (); }    }}

Resources

Page 827, resolving shared resource contention, thinking in Java

[Java Concurrent] A simple case of concurrent access to shared resources

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.