一些影响线程状态的方法(Object类对多线程的支持)

public final void wait() throws InterruptedException 线程等待,Thread.sleep()和Thread对象.wait()都会堵塞线程,区别在于sleep到时间后会自动恢复,wait要notify通知才可以恢复
public final native void notify() 唤醒第一个等待线程
public final native void notifyAll() 唤醒全部等待线程

推荐的停止线程方法

Thread中的suspend()、resume()和stop方法不推荐使用 , 主要因为这三个方法在操作时会产生死锁的问题.

开发时建议使用设置标志位的方式停止一个线程的运行.
下面这个方法也证明了synchronized锁定的是对象锁,不是对象中具体的某个变量.**

  1. public class Test extends Object {
  2. public static void main(String[] args) throws Exception {
  3. MyThread myThread=new MyThread();
  4. Thread thread=new Thread(myThread);
  5. thread.start();
  6. Thread.currentThread().sleep(3000);
  7. myThread.stop();
  8. }
  9. }
  10. class MyThread implements Runnable {
  11. private boolean flag = true;
  12. @Override
  13. public void run() {
  14. this.begin();
  15. }
  16. public void stop() {
  17. this.flag=false;
  18. }
  19. private synchronized void begin() {
  20. int i=0;
  21. while (flag) {
  22. System.out.println(Thread.currentThread().getName() + i++);
  23. }
  24. }
  25. }