多线程之休眠(sleep())
sleep()方法会使当前线程由运行状态进入到休眠(阻塞)状态同时让出CPU资源,休眠结束后,就会由阻塞状态变为就绪状态,竞争CPU资源,整个过程都会持有对象锁——(当前线程的代码会执行完毕,然后执行sleep()方法所在线程代码)——(相当于异步阻塞)
private static List obj = new ArrayList<>(10);
@Override
public void run() {
synchronized (obj){
for(int i=0;i<10;i++){
try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
obj.add(“123”);
System.out.println(Thread.currentThread().getName()+”—-“+i);
}
}
}
public static void main(String[] args) {
thread3 t = new thread3();
Thread threa = new Thread(t);
Thread threaa = new Thread(t);
threa.start();
threaa.start();