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