方法 | 说明 |
start | |
sleep | |
run | 线程执行的业务逻辑应该在这里实现。 |
join | |
yield | |
wait | |
notify | |
notifyAll | |
interrupt | 中断线程。 |
方法 | 说明 |
stop | 强制使当前的线程停止执行。实际上,作为开发人员我们会意识到,线程的复杂程度是没有边际的,而这个方法这样武断的停止一个线程,必然导致问题产生。也就是说,这个方法天生就有问题。比如说一个线程掌握了很多对象,并且改变了其中一些的状态,如果突然当前对象突然被停止,将会释放这些对象的monitor,这个时候被改变状态的对象就是被损坏的对象,其他线程再来操作的时候问题就出来了。 替代的办法就是让当前线程正常结束,不使用这个方法。就是我们设置一些标志,如果这些标志满足的时候,我们结束线程。下面用JDK的例子: private Thread blinker; public void start() { blinker = new Thread(this); blinker.start(); } public void stop() { blinker.stop(); // UNSAFE! } public void run() { Thread thisThread = Thread.currentThread(); while (true) { try { thisThread.sleep(interval); } catch (InterruptedException e){ } //do something } }修改后: private volatile Thread blinker; public void stop() { blinker = null; } public void run() { Thread thisThread = Thread.currentThread(); //Check the flag while (blinker == thisThread) { try { thisThread.sleep(interval); } catch (InterruptedException e){ } //do something }} 当然如果这个方法中间有wait方法的调用的话,而且正在等待,我们可以使用这个办法来结束: Thread.currentThread().interrupt(); 然后处理InterruptedException 这个我也实现了避免使用stop方法的一个类,在源码中可以看到。 |
suspend | 这个方法天生就有导致死锁的可能。如果当前线程持有很多对象的锁,但是当他suspend的时候,这些锁是不会释放的,想想就知道应该什么可能会发生,所以这个方法应该尽量不用。 这里我们有办法替代这个方法,其实根替代stop的方法差不多,就是用wait方法来实现挂起,而不是事实上的挂起。比如: @Override @SuppressWarnings("static-access") public void run() { while (true) { try { Thread.currentThread().sleep(1000); // Double check if (isSuspended) { synchronized (this) { while (isSuspended) { wait(); } } } } catch (InterruptedException e) { // null } } } 这样做可以同样实现挂起,但是仍然会释放资源。 |
resume |
关键字 | 说明 |
volatile | 这个关键字告诉编译器不要对这个属性或者值进行优化,也就是为了保证这个变量的同步性,如果这个值被更新,其他线程应该可以马上访问到最新的值,而不是“脏值”。其实这个关键字是同步互斥的一个模型,但是现在没有实现。 |
synchronized | 给对象或者Class加锁,分为对象锁和Class锁。 对象锁只是加在当前对象上,对别的对象没有影响,这种加锁一般都是把这个关键字用在方法和同步块上面。 Class锁就是加在这个Class上面,所有的其他对象想访问这个Class的对象的任何同步方法,必须获得这个锁。这种锁一般把这个关键字用在静态方法中,或者显示的这样实现: synchronized (AClass.class) { while (isSuspended) { wait(); } } 一般我们很少用Class锁。 这里简单提一下monitor,个人感觉这里把monitor认为是一把锁也可以。网络上有朋友解释的比较好:在Java中,每个对象只有一个相应的monitor,一个mutex,而每一个monitor都可以有多个“doors”可以进入,即,同一个monitor中被守护的代码可以在不同的地方,因为同一个对象可以出现在不同的代码段,只要mutex锁定的对象是同一个,每个入口都用Synchronized关键字表明,当一个线程通过了Synchronized关键字,它就所住了该monitor所有的doors |
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |