public class Test176 {
synchronized public void show() {
String s1 = "这是处理的任务1"+Thread.currentThread().getName();
String s2 = "这是处理的任务2"+Thread.currentThread().getName();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(s1);
System.out.println(s2);
}
}
package com.example.test;
public class Test177 {
public static void main(String[] args) {
Test176 t = new Test176();
MyThreadSix mts = new MyThreadSix(t);
Thread t1 = new Thread(mts);
Thread t2 = new Thread(mts);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
}
class MyThreadSix implements Runnable{
private Test176 t;
public MyThreadSix(Test176 t) {
super();
this.t = t;
}
@Override
public void run() {
// TODO Auto-generated method stub
System.out.println(Thread.currentThread().getName()+"开始时间"+System.currentTimeMillis());
t.show();
System.out.println(Thread.currentThread().getName()+"结束时间"+System.currentTimeMillis());
}
}
在上述的代码中,用时间毫秒数大的结束时间-时间毫秒数小的开始时间得出两个线程全部完成的总时间。
将代码修改如下:
public void show() {
String s1 = "这是处理的任务1"+Thread.currentThread().getName();
String s2 = "这是处理的任务2"+Thread.currentThread().getName();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized (this) {
System.out.println(s1);
System.out.println(s2);
}
}
你在运行,会发现,执行时间短了。这也引出了synchronized 代码块执行效率比synchronized 修饰方法要高。
但是我们要搞清楚,为啥呢,synchronized 修饰方法,那么另外线程就必须等待整个方法执行完毕,你要知道一些方法可能有一些耗时操作,这些耗时操作可以异步做,主要是在获取数据,或者关键的修改地方是必须同步,所以你何苦要封锁整个方法。通过本文的例子,希望能理解这点。