Java thread deadlock Simulation

Source: Internet
Author: User

1. About deadlock

Deadlock, we can simply understand that two threads use the same resource at the same time, and the two threads do not get the corresponding resources, resulting in no waiting for each other.

2. simulate a deadlock

Background: we create a friend class. When a friend bows to us, we also bow to our friends. This is a complete action. When two

While bowing, waiting for the other party to bow. A deadlock occurs.

Simulation Program:

Package com. yxy. thread; /*** @ author windows * Deadlock Simulation Program */public class Deadlock {/*** @ author windows * Friend entity class */static class Friend {// Friend name private final string name; // construct a Friend object type public Friend (String name) {this. name = name;} // obtain the public String getName () {return this. name ;}// a Friend bows to me (synchronous) public synchronized void bow (Friend bower) {System. out. format ("% s: % s" + "has bowed to me! % N ", this. name, bower. getName (); bower. bowBack (this);} // method of bowing (synchronous) public synchronized void bowBack (Friend bower) {System. out. format ("% s: % s" + "has bowed back to me! % N ", this. name, bower. getName () ;}} public static void main (String [] args) {// deadlock simulation program test start // create two friends alphonse, gaston final Friend alphonse = new Friend ("Alphonse"); final Friend gaston = new Friend ("Gaston"); // start the thread of two friends bowing. New Thread (new Runnable () {public void run () {alphonse. bow (gaston );}}). start (); new Thread (new Runnable () {public void run () {gaston. bow (alphonse );}}). start ();}}


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.