Java thread (15): Concurrent collaboration-deadlock

Source: Internet
Author: User

Java threads: Concurrent collaboration-deadlock threads are unlikely to experience deadlocks. Even code that appears to have deadlocks, the possibility of deadlocks at run time is also small. The cause of the deadlock is generally caused by mutual lock wait between two objects. In the article "Java thread: synchronization and lock of Threads", the concept and simple example of deadlock are briefly described, but the example given is incomplete. Here is a complete example. /*** Java thread: Concurrent collaboration-deadlock ** @ author Administrator 22:06:13 */public class Test {public static void main (String [] args) {DeadlockRisk dead = new DeadlockRisk (); MyThread t1 = new MyThread (dead, 1, 2); MyThread t2 = new MyThread (dead, 3, 4 ); myThread t3 = new MyThread (dead, 5, 6); MyThread t4 = new MyThread (dead, 7, 8); t1.start (); t2.start (); t3.start (); t4.start () ;}} class MyThread ext Ends Thread {private DeadlockRisk dead; private int a, B; MyThread (DeadlockRisk dead, int a, int B) {this. dead = dead; this. a = a; this. B = B ;}@ Override public void run () {dead. read (); dead. write (a, B) ;}} class DeadlockRisk {private static class Resource {public int value;} private Resource resourceA = new Resource (); private Resource resourceB = new Resource (); public int read () {synch Ronized (resourceA) {System. out. println ("read ():" + Thread. currentThread (). getName () + "gets the resourceA lock! "); Synchronized (resourceB) {System. out. println (" read (): "+ Thread. currentThread (). getName () +" gets the resourceB lock! "); Return resourceB. value + resourceA. value ;}} public void write (int a, int B) {synchronized (resourceB) {System. out. println ("write ():" + Thread. currentThread (). getName () + "gets the resourceA lock! "); Synchronized (resourceA) {System. out. println (" write (): "+ Thread. currentThread (). getName () +" gets the resourceB lock! "); ResourceA. value = a; resourceB. value = B ;}}}}

Related Article

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.