
上QQ阅读APP看书,第一时间看更新
2.1.10 非同步方法:不使用synchronized重写方法
重写方法如果不使用synchronized关键字,即非同步方法,使用后变成同步方法。
创建测试项目synNotExtends,类Main.java代码如下:
package service; public class Main { synchronized public void serviceMethod() { try { System.out.println("int main 下一步sleep begin threadName=" + Thread.currentThread().getName() + " time=" + System.currentTimeMillis()); Thread.sleep(5000); System.out.println("int main 下一步sleep end threadName=" + Thread.currentThread().getName() + " time=" + System.currentTimeMillis()); } catch (InterruptedException e) { e.printStackTrace(); } } }
类Sub.java代码如下:
package service; public class Sub extends Main { @Override public void serviceMethod() { try { System.out.println("int sub 下一步sleep begin threadName=" + Thread.currentThread().getName() + " time=" + System.currentTimeMillis()); Thread.sleep(5000); System.out.println("int sub 下一步sleep end threadName=" + Thread.currentThread().getName() + " time=" + System.currentTimeMillis()); super.serviceMethod(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
类MyThreadA.java和MyThreadB.java代码如图2-17所示。

图2-17 两个线程代码
类Test.java代码如下:
package controller; import service.Sub; import extthread.MyThreadA; import extthread.MyThreadB; public class Test { public static void main(String[] args) { Sub subRef = new Sub(); MyThreadA a = new MyThreadA(subRef); a.setName("A"); a.start(); MyThreadB b = new MyThreadB(subRef); b.setName("B"); b.start(); } }
程序运行结果如图2-18所示。

图2-18 运行效果
从输出结果可以看到,这里是以异步方式输出,所以还得在子类的重写方法中添加synchronized关键字,如图2-19所示。

图2-19 同步输出