关于synchronized ,我现在还处于学习阶段。
下面给一段实例:
1 public class Test extends Thread{ 2 private String name; 3 public Test(){ 4 5 } 6 public Test(String name){ 7 this.name = name; 8 } 9 public void run(){ 10 for(int i =0;i<5;i++){ 11 System.out.println(name+"运行 "+i); 12 } 13 } 14 15 public static void main(String[] args){ 16 Test t1 = new Test("A"); 17 Test t2 = new Test("B"); 18 t1.start(); 19 t2.start(); 20 } 21 }
结果是:
A运行 0
B运行 0
A运行 1
B运行 1
A运行 2
B运行 2
A运行 3
B运行 3
A运行 4
B运行 4
可以看出,线程A和线程B是同步执行的。
那么如果我在run()方法上加上synchronized ,那么run()方法就被加上锁。这就意味着,只有A线程执行完之后,才能轮到线程B执行。
我们在原有的代码上加上synchronized修饰符。
1 public synchronized void run(){ 2 for(int i =0;i<5;i++){ 3 System.out.println(name+"运行 "+i); 4 } 5 }
执行完之后,可以发现线程A和线程B变成异步执行了:
A运行 0
A运行 1
A运行 2
A运行 3
A运行 4
B运行 0
B运行 1
B运行 2
B运行 3
B运行 4