打字猴:1.700450951e+09
1700450951
1700450952 //内部锁任务
1700450953
1700450954 class TaskWithSync extends Task implements Runnable{
1700450955
1700450956 @Override
1700450957
1700450958 public void run(){
1700450959
1700450960 //内部锁
1700450961
1700450962 synchronized(“A”){
1700450963
1700450964 doSomething();
1700450965
1700450966 }
1700450967
1700450968 }
1700450969
1700450970 }
1700450971
1700450972 这两个任务看着非常相似,应该能够产生相似的结果吧?我们建立一个模拟场景,保证同时有三个线程在运行,代码如下:
1700450973
1700450974 public static void runTasks(Class<?extends Runnable>clz)throws Exception{
1700450975
1700450976 ExecutorService es=Executors.newCachedThreadPool();
1700450977
1700450978 System.out.println(”***开始执行”+clz.getSimpleName()+“任务****”);
1700450979
1700450980 //启动三个线程
1700450981
1700450982 for(int i=0;i<3;i++){
1700450983
1700450984 es.submit(clz.newInstance());
1700450985
1700450986 }
1700450987
1700450988 //等待足够长的时间,然后关闭执行器
1700450989
1700450990 TimeUnit.SECONDS.sleep(10);
1700450991
1700450992 System.out.println(”––”+clz.getSimpleName()+“任务执行完毕–—\n”);
1700450993
1700450994 //关闭执行器
1700450995
1700450996 es.shutdown();
1700450997
1700450998 }
1700450999
1700451000 public static void main(String[]args)throws Exception{
[ 上一页 ]  [ :1.700450951e+09 ]  [ 下一页 ]