synchronized 通常用来形容一次方法的调用,调用一旦开始,调用者必须等到方法调用返回后,才能继续执行后续的操作。
1.demo
package demo1; public class MyThread extends Thread { private int count = 5; @Override public void run() { count--; System.err.println("∽"+currentThread().getName()+"count:"+this.count); } public static void main(String[] args){ MyThread myThread = new MyThread(); Thread t1 = new Thread(myThread,"myThread-1"); Thread t2 = new Thread(myThread,"myThread-2"); Thread t3 = new Thread(myThread,"myThread-3"); Thread t4 = new Thread(myThread,"myThread-4"); Thread t5 = new Thread(myThread,"myThread-5"); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); } }
结果输出:
∽myThread-1count:2
∽myThread-4count:1
∽myThread-2count:2
∽myThread-3count:2
∽myThread-5count:0
描述:5个线程都会去对这个 count 变量进行操作,但是出现了重复的数据,说明没有进行同步、共享。
2.demo:使用 synchronized 关键字
package demo1; public class MyThread extends Thread { private int count = 5; @Override public synchronized void run() { count--; System.err.println("∽"+currentThread().getName()+"count:"+this.count); } public static void main(String[] args){ MyThread myThread = new MyThread(); Thread t1 = new Thread(myThread,"myThread-1"); Thread t2 = new Thread(myThread,"myThread-2"); Thread t3 = new Thread(myThread,"myThread-3"); Thread t4 = new Thread(myThread,"myThread-4"); Thread t5 = new Thread(myThread,"myThread-5"); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); } }
结果输出:
∽myThread-1count:4
∽myThread-3count:3
∽myThread-2count:2
∽myThread-4count:1
∽myThread-5count:0
描述:输出的结果没有重复的,说明同步生效了。
1.当多个线程都去访问 MyThread 的run 方法的时候,都会以队列的的方式去进行访问处理(CPU的分配)。
2.一个线程要执行 synchronized 方法修饰的代码块:都会去尝试去获取锁(object的锁),如果拿到锁,则执行 synchronized 代码的内容;
如果拿不到,则会不断的去尝试获取这把锁,一直到拿到为止 (多个线程去尝试获取这把锁,就行形成竞争、排队的问题)。
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/16274.html