打字猴:1.700450889e+09
1700450889
1700450890 Thread.sleep(2000);
1700450891
1700450892 }catch(Exception e){
1700450893
1700450894 //异常处理
1700450895
1700450896 }
1700450897
1700450898 StringBuffer sb=new StringBuffer();
1700450899
1700450900 //线程名称
1700450901
1700450902 sb.append(“线程名称:”+Thread.currentThread().getName());
1700450903
1700450904 //运行的时间戳
1700450905
1700450906 sb.append(”,执行时间:”+Calendar.getInstance().get(13)+“s”);
1700450907
1700450908 System.out.println(sb);
1700450909
1700450910 }
1700450911
1700450912 }
1700450913
1700450914 该类模拟了一个执行时间比较长的计算,注意这里使用的是模拟方式,在使用sleep方法时线程的状态会从运行状态转变为等待状态。该任务要具备多线程能力时必须实现Runnable接口,我们分别建立两种不同的锁实现机制,首先看显式锁实现:
1700450915
1700450916 //显式锁任务
1700450917
1700450918 class TaskWithLock extends Task implements Runnable{
1700450919
1700450920 //声明显式锁
1700450921
1700450922 private fnal Lock lock=new ReentrantLock();
1700450923
1700450924 @Override
1700450925
1700450926 public void run(){
1700450927
1700450928 try{
1700450929
1700450930 //开始锁定
1700450931
1700450932 lock.lock();
1700450933
1700450934 doSomething();
1700450935
1700450936 }finally{
1700450937
1700450938 //释放锁
[ 上一页 ]  [ :1.700450889e+09 ]  [ 下一页 ]