synchronized different scenarios of different uses

The main article is synchronized given in different scenes snippets of different uses, can be run directly after compiling, do not understand people who can run this code after learning the synchronized keyword, there will be an epiphany-like feeling oh


/ **
* method1 and method2 is to solve different threads operating on the same object of a class
* method3 and method4 to solve different threads operating on different objects of the same class
* @author Liang
* @Since 2019-08-06 17:54
* /
public class SynchronizedMethodDemo the implements the Runnable {

static SynchronizedMethodDemo synchronizedMethodDemo0 new new SynchronizedMethodDemo = ();
static SynchronizedMethodDemo synchronizedMethodDemo1 new new SynchronizedMethodDemo = ();

@Override
public void RUN () {
// the method1 ();
// method2 ();
/ / the method3 ();
method4 ();
}

/ **
* the method1 method2 with two different writing the same code
* method referred object is synchronized default the this
* /
Private the synchronized void the method1 () {
System.out.println ( "I Thread" + Thread.currentThread () getName ().);
the try {
the Thread.sleep (2000);
} the catch (InterruptedException E) {
e.printStackTrace ( );
}
}

Private void method2 () {
the synchronized (the this) {
System.out.println ( "I am the thread" + Thread.currentThread () getName ());.
the try {
Thread.sleep (2000);
} the catch ( E InterruptedException) {
e.printStackTrace ();
}
}
}

/ **
* when the two methods of access to different threads of different objects of the same class
* 1. synchronized (*.class)代码段
* 2. static synchronized 方法
*/
private void method3() {
synchronized (SynchronizedMethodDemo.class){
System.out.println("我是线程"+Thread.currentThread().getName());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

private static synchronized void method4() {
System.out.println("我是线程"+Thread.currentThread().getName());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
     // commented multithreading part of the same object 
     // = the Thread new new Thread0 the Thread (synchronizedMethodDemo0);
     // = the Thread new new Thread1 the Thread (synchronizedMethodDemo0);
        Thread thread0 = new Thread(synchronizedMethodDemo0);
Thread thread1 = new Thread(synchronizedMethodDemo1);

thread0.start();
thread1.start();

}
}

Guess you like

Origin www.cnblogs.com/cnliang/p/11310998.html