JAVA thread deadlock, java thread

Source: Internet
Author: User

JAVA thread deadlock, java thread

File Name: DeadThreadByExtend. java

Note:

1. When starting a thread, the start method is used. The run method can also be called, but it is only equivalent to a common call and executed in the current thread.

2. synchronized cannot directly modify variables.

3. synchronized blocks do not force single-thread access to the variables in the blocks. It only means that the synchronized (args) parameter is locked when the block statement is executed and is released until the execution ends.

Package com. ycf. study. thread; class Sources {int a; public void setA (int x) {synchronized (this) {this. a = x; try {Thread. sleep (2000);} catch (InterruptedException e) {e. printStackTrace () ;}}} public class DeadThreadByExtend {public static void main (String [] args) {Sources s1 = new Sources (); Sources s2 = new Sources (); class MyThread1 extends java. lang. thread {@ Override public void run () {System. out. println ("thread 1 start"); synchronized (s1) {System. out. println ("thread 1 applying to modify s1"); s1.setA (20); System. out. println ("thread 1 modified"); System. out. println ("thread 1 request to modify s2"); s2.setA (10); System. out. println ("thread 1 s2 modified");} System. out. println ("thread 1 exits and releases the lock ++");} class MyThread2 extends java. lang. thread {@ Override public void run () {System. out. println ("thread 2 starts"); synchronized (s2) {System. out. println ("thread 2 apply to modify s2"); s2.setA (20); System. out. println ("thread 2 completes s2 modification"); System. out. println ("thread 2 applying to modify s1"); s1.setA (10); System. out. println ("thread 2 modifying s1 completed");} System. out. println ("thread 2 exits and releases the lock ++") ;}} MyThread1 mt1 = new MyThread1 (); MyThread2 mt2 = new MyThread2 (); mt1.start (); mt2.start ();}}
Java Learning Group 669823128

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.