本文主要给出的是synchronized在不同场景中的不同用法的代码段,可直接编译后运行,不理解的人可以在学习synchronized关键字后再运行此代码,会有顿悟般的感觉哦
/**
* method1与method2是为了解决不同线程对一个类的同一个对象的操作
* method3与method4是为了解决不同线程对同一个类不同对象的操作
* @author Liang
* @since 2019-08-06 17:54
*/
public class SynchronizedMethodDemo implements Runnable {
static SynchronizedMethodDemo synchronizedMethodDemo0 = new SynchronizedMethodDemo();
static SynchronizedMethodDemo synchronizedMethodDemo1 = new SynchronizedMethodDemo();
@Override
public void run() {
// method1();
// method2();
// method3();
method4();
}
/**
* method1与method2是同一段代码的两种不同写法
* 方法中synchronized默认所指的对象是this
*/
private synchronized void method1() {
System.out.println("我是线程"+Thread.currentThread().getName());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void method2() {
synchronized (this){
System.out.println("我是线程"+Thread.currentThread().getName());
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/**
* 对不同线程访问同一个类不同对象时的两种方式
* 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) {
// 注释掉的部分是多线程对同一对象的操作
// Thread thread0 = new Thread(synchronizedMethodDemo0);
// Thread thread1 = new Thread(synchronizedMethodDemo0);
Thread thread0 = new Thread(synchronizedMethodDemo0);
Thread thread1 = new Thread(synchronizedMethodDemo1);
thread0.start();
thread1.start();
}
}
原文:https://www.cnblogs.com/cnliang/p/11310998.html