Java thread sharing restricted resources solve resource competition thinking in java4 21.3, vpn thread Limited

Source: Internet
Author: User

Java thread sharing restricted resources solve resource competition thinking in java4 21.3, vpn thread Limited

Java threads share restricted resources to solve resource competition details, see thinking in java4 21.3

Thinking in java 4 free download: http://download.csdn.net/detail/liangrui1988/7580155

Package org. rui. thread. res;/*** incorrect Resource Access * @ author lenovo **/public abstract class IntGenerator {private volatile boolean canceled = false; // The canceled public abstract int next (); // This type of cancelpublic void cancel () {canceled = true;} public boolean isCanceled () {return canceled ;}}

Package org. rui. thread. res; import java. util. concurrent. executorService; import java. util. concurrent. executors;/*** any IntGenerator can use the following EvenCherker class to test * @ author lenovo **/public class EvenChecker implements Runnable {private IntGenerator generator; private final int id; public EvenChecker (IntGenerator g, int ident) {this. generator = g; this. id = ident ;}@ Overridepublic void run () {while (! Generator. isCanceled () {int val = generator. next (); if (val % 2! = 0) {System. out. println (val + "not even! "); Generator. cancel (); // cancels all evencheckers }}// test any type of intgeneratorpublic static void test (IntGenerator gp, int count) {System. out. println ("press control-c to exit"); ExecutorService ex = Executors. newCachedThreadPool (); for (int I = 0; I <count; I ++) {ex.exe cute (new EvenChecker (gp, I);} ex. shutdown ();/* for (int I = 0; I <count; I ++) {Thread t = new Thread (new EvenChecker (gp, I); t. start () ;}* // public static void test (IntGenerator gp) {test (gp, 10 );}}

Package org. rui. thread. res;/*** this program will eventually fail, because the evenChecker task is still able to access the information when the evenGenerator is in an inappropriate state. * if you want to detect failure more quickly, you can try to place the yield () call between the first and second incremental operations. * This is only part of the concurrent program * @ author lenovo **/public class EvenGenerator extends IntGenerator {private int currentEvenValue = 0; @ Overridepublic int next () {++ currentEvenValue; // dangerous project publications! Danger point here ++ currentEvenValue; return currentEvenValue;} public static void main (String [] args) {EvenChecker. test (new EvenGenerator () ;}}/*** output: press control-c to exit13103419 not even! */

Package org. rui. thread. res;/*** synchronous control EvenGenerator * @ author lenovo **/public class SynchronizedEvenGenerator extends IntGenerator {private int currentEvenValue = 0; @ Overridepublic synchronized int next () {++ currentEvenValue; thread. yield (); // cause the failed thread to pause the currently executing thread object faster and execute other threads. ++ CurrentEvenValue; return currentEvenValue;} public static void main (String [] args) {EvenChecker. test (new SynchronizedEvenGenerator () ;}/ ** output: press control-c to exit */

Package org. rui. thread. res; import java. util. concurrent. locks. lock; import java. util. concurrent. locks. reentrantLock;/*** use the displayed Lock Object * @ author lenovo **/public class MutexEvenGenerator extends IntGenerator {private int currentEvenValue = 0; Lock lock Lock = new ReentrantLock (); @ Overridepublic int next () {lock. lock (); try {++ currentEvenValue; Thread. yield (); // cause the failed thread to pause the currently executing thread object faster and execute other threads. ++ CurrentEvenValue; return currentEvenValue;} finally {lock. unlock ();}} /// // public static void main (String [] args) {EvenChecker. test (new MutexEvenGenerator () ;}/ ** output: press control-c to exit */

Package org. rui. thread. res; import java. util. concurrent. timeUnit; import java. util. concurrent. locks. reentrantLock;/*** the synchronized keyword cannot try to get the lock and the final acquisition will fail * or both attempt to get the lock for a period of time, and then discard it. To implement this, you must use the concurrent Class Library: *** ReentrantLock allows you to try to obtain the lock, but the lock is obtained at the end, so that if someone else has obtained the lock, * Then you can decide to leave and execute other events, instead of waiting until the lock is released, as shown in the untimed () method. * Try to get the lock in timed, this attempt may fail in 2 seconds * @ author lenovo **/public class AttemptLocking {// reentrant mutex lock private ReentrantLock lock = new ReentrantLock (); public void untimed () // No-timing {// The lock is obtained only when the lock is not kept by another thread during the call. Boolean captured = lock. tryLock (); try {System. out. println ("tryLock ():" + captured);} finally {if (captured) lock. unlock () ;}///// // public void timed () // timing {boolean captured = false; try {// If the lock is not kept by another thread within the specified wait time and the current thread is not interrupted, the lock is obtained. Captured = lock. tryLock (2, TimeUnit. SECONDS);} catch (InterruptedException e) {throw new RuntimeException (e);} try {System. out. println ("tryLock (2, TimeUnit. SECONDS): "+ captured);} finally {if (captured) lock. unlock () ;}//// // mainpublic static void main (String [] args) throws InterruptedException {final AttemptLocking al = new AttemptLocking (); al. untimed (); // true -- lock is available lock available al. timed (); // tr Ue -- lock is available // now create a separate task to obtain the lock, so that the following Thread calls compete in new Thread () {setDaemon (true) ;}@ Overridepublic void run () {al. lock. lock (); System. out. println ("acquired ");}}. start (); Thread. sleep (1000); // pause the currently executing thread object and execute other threads. // Thread. yield (); // give the 2nd task a chance to give the second task a chance to al. untimed (); // false -- lock grabbed by task locked task al. timed (); // false -- lock grabbed by task}/*** output: tryLock (): truetryLock (2, TimeUnit. SECONDS): trueacquiredtryLock (): falsetryLock (2, TimeUnit. SECONDS): false */



JAVA multi-thread resource sharing and deadlock issues. Thread thread1 = new Thread (new Test (true ));

Flag true in the object; Lock. lock1 is obtained.
Lock
Thread thread2 = new Thread (new Test (false ));

Flag false in the object; Lock. lock2 is obtained.
Lock
Thread1 again wants to get Lock. lock2
Code:
Synchronized (Lock. lock2 ){
System. out. println ("if-lock2 ");
}

Thread2 again wants to get Lock. lock1
Code: synchronized (Lock. lock1 ){
System. out. println ("else-lock1 ");
}
Mutual wait forms a deadlock
Ask thinking in java 4 English chm format http://www.shubulo.com/viewthread.php? Tid = 35514

Score it ..

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.