java interrupted使用
1 interruped java中当一个线程sleep时,调用其中断方法是无效的,因此在异常的处理中需要将线程interrupt(),否则线程依然是非interrupt状态。 下面的例子中,线程将进入死循环,不会退出,因为主线程调用了interrupt()方法时,线程s正在睡眠。 正确的方法应该在异常中调用Thread.currentThread().interrupt(); public static void main(String[] args) throws InterruptedException { Thread s = new Thread(){ public void run(){ while(!interrupted()){ System.out.println("------"); try{ sleep(5000); } catch (InterruptedException e) { //Thread.currentThread().interrupt(); System.out.println("异常"); } System.out.println("......."); } } }; s.start();
Thread.currentThread().sleep(2000);
s.interrupt();
}
2.synchronized与wait区别 synchronized不会让线程进入对象的等待队列,线程不会停止,而wait表示将线程放入到对象的等待队列中,只有当其他的线程调用了notify,notifyAll时,jvm才会调度该线程 3.静态synchronized synchronized表示同步的对象为当前对象,静态synchronized表示锁定的是class对象 4.stop方法用来停止线程不安全,当一个线程被stop时,它会立即释放它锁定的所有对象的锁,这会使得各个对象处于不一致的状态中,要停止一个线程,使用一个变量来标示