synchronized 在多线程中的一些 理论

来源:互联网 发布:网络舆论使思考更多元 编辑:程序博客网 时间:2024/05/22 04:33
package com.mhm.test;public class Test8 extends Thread {public String methodName;public static void method(String s) {System.out.println(s);while (true);}public synchronized void method1() {method("非静态的method1方法");}public synchronized void method2() {method("非静态的method2方法");}public static synchronized void method3() {method("静态的method3方法");}public static synchronized void method4() {method("静态的method4方法");}public void run() {try {getClass().getMethod(methodName).invoke(this);} catch (Exception e) {}}public static void main(String[] args) throws Exception {Test8 myThread1 = new Test8();for (int i = 1; i <= 4; i++) {myThread1.methodName = "method" + String.valueOf(i);new Thread(myThread1).start();sleep(100);}}}
 

 

 

输出

非静态的method1方法静态的method3方法

 

得出结果:

method2和method4在method1和method3未结束之前不能运行。因此,我们可以得出一个结论,如果在类中使用synchronized关键字来定义非静态方法,那将影响这个中的所有使用synchronized关键字定义的非静态方法。如果定义的是静态方法,那么将影响类中所有使用synchronized关键字定义的静态方法

原创粉丝点击