一个类有两个方法,其中一个是同步的,另一个是非同步的;
现在又两个线程A和B,请问:当线程A访问此类的同步方法时,线程B是否能访问此类的非同步方法?答案:可以
验证
package com.my.test2;public class ClassA { public synchronized void do1() { //延迟打印,为了更明显 try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("synchronized do1"); } public void do2() { System.out.println("do2"); } }package com.my.test2;public class Thread1 extends Thread{ private ClassA classA; public Thread1(ClassA classA) { this.classA = classA; } @Override public void run() { classA.do1(); }}package com.my.test2;public class Thread2 extends Thread{ private ClassA classA; public Thread2(ClassA classA) { this.classA = classA; } @Override public void run() { classA.do2(); }}package com.my.test2;public class Test { /** * @param args */ public static void main(String[] args) { ClassA classA = new ClassA(); Thread1 thread1 = new Thread1(classA); Thread2 thread2 = new Thread2(classA); thread1.start(); thread2.start(); }}
执行结果:
do2
synchronized do1 //延迟3秒后输出