按理说在synchronized使用sleep方法,该线程应该不会释放锁,可是如果是执行时间+休眠时间过长的话,超过了cup的时间片的时间,这个时候,这个线程便会被其他线程所竞争。应该是操作系统的操作
以下是代码:
首先是锁对象
下面展示一些 内联代码片
。
package com.cn; public class Obj { public int count=1; }
线程a
package com.cn; public class Theada implements Runnable { private Obj ss; public Theada(Obj ss) { this.ss = ss; } @Override public void run() { while (true){ synchronized (ss){ System.out.println("a:"+ss.count); ss.count++; try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } if (ss.count>10){ System.exit(0); } } } } } ;
线程b
package com.cn; public class Theadb implements Runnable { private Obj ss; public Theadb(Obj ss) { this.ss = ss; } @Override public void run() { while (true){ synchronized (ss){ System.out.println("b:"+ss.count); ss.count++; try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } if (ss.count>10){ System.exit(0); } } } } }
main方法
package com.cn; public class Test { public static void main(String[] args) { Obj obj=new Obj(); Theada theada=new Theada(obj); Theadb theadb=new Theadb(obj); Thread thread=new Thread(theada); Thread threadb=new Thread(theadb); thread.start(); threadb.start(); } }