Synchronized使用的三种方式:
- synchronized代码块-----可以指定任意对象,和synchronized方法联用要指向当前对象this
- synchronized方法-----this当前对象
- synchronized静态方法-----该类的字节码对象
测试类:
public class SynSample { public static void main(String[] args) { Couplet couplet = new Couplet(); for (int i = 0; i < 10000; i++) { new Thread() { public void run() { int r = new Random().nextInt(2); if (r % 2 == 0) { couplet.first(); } else { couplet.second(); } } }.start(); } } }
1.synchronized代码块
需要指向同一对象
class Couplet { Object lock = new Object(); public void first() { synchronized (lock) { System.out.print("琴"); System.out.print("瑟"); System.out.print("琵"); System.out.print("琶"); System.out.println(); } } public void second() { synchronized (lock) { System.out.print("魑"); System.out.print("魅"); System.out.print("魍"); System.out.print("魉"); System.out.println(); } } }
2.synchronized方法
class Couplet { Object lock = new Object(); public synchronized void first() { System.out.print("琴"); System.out.print("瑟"); System.out.print("琵"); System.out.print("琶"); System.out.println(); } public synchronized void second() { System.out.print("魑"); System.out.print("魅"); System.out.print("魍"); System.out.print("魉"); System.out.println(); } }
两种混用
class Couplet { Object lock = new Object(); public synchronized void first() { System.out.print("琴"); System.out.print("瑟"); System.out.print("琵"); System.out.print("琶"); System.out.println(); } public void second() { synchronized (this) { System.out.print("魑"); System.out.print("魅"); System.out.print("魍"); System.out.print("魉"); System.out.println(); } } }
3.synchronized静态方法
测试类改静态调用:
public class SynSample { public static void main(String[] args) { Couplet couplet = new Couplet(); for (int i = 0; i < 10000; i++) { new Thread() { public void run() { int r = new Random().nextInt(2); if (r % 2 == 0) { Couplet.first(); } else { Couplet.second(); } } }.start(); } } }
class Couplet { Object lock = new Object(); public synchronized static void first() { System.out.print("琴"); System.out.print("瑟"); System.out.print("琵"); System.out.print("琶"); System.out.println(); } public synchronized static void second() { System.out.print("魑"); System.out.print("魅"); System.out.print("魍"); System.out.print("魉"); System.out.println(); } }
混用
class Couplet { Object lock = new Object(); public synchronized static void first() { System.out.print("琴"); System.out.print("瑟"); System.out.print("琵"); System.out.print("琶"); System.out.println(); } public static void second() { synchronized (Couplet.class) { System.out.print("魑"); System.out.print("魅"); System.out.print("魍"); System.out.print("魉"); System.out.println(); } } }
标签:synchronized,void,System,关于,使用,print,public,out From: https://www.cnblogs.com/blanset/p/16774550.html