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