一些影响线程状态的方法(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锁定的是对象锁,不是对象中具体的某个变量.**
public class Test extends Object {
public static void main(String[] args) throws Exception {
MyThread myThread=new MyThread();
Thread thread=new Thread(myThread);
thread.start();
Thread.currentThread().sleep(3000);
myThread.stop();
}
}
class MyThread implements Runnable {
private boolean flag = true;
@Override
public void run() {
this.begin();
}
public void stop() {
this.flag=false;
}
private synchronized void begin() {
int i=0;
while (flag) {
System.out.println(Thread.currentThread().getName() + i++);
}
}
}