- <div class="blockcode"><blockquote>package cn.itcast.thread;
- /*
- * 线程终止的第二种情况,对于等待中的线程,用的是interrupt()方法终止线程。
- */
- public class InterruptThreadDemo2 {
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- InterruptThread2 it=new InterruptThread2(true);
-
- Thread t=new Thread(it);
- t.start();
-
- for(int i=0;i<100000;i++){
- if(i==99999)
- it.flag=false;
- }
- }
- }
- class InterruptThread2 implements Runnable{
- boolean flag=true;
- InterruptThread2(boolean flag){
- this.flag=flag;
- }
- public void run(){
- while(flag){
- //这个wait()方法为什么要方法同步下呢?跟谁同步啊,这是?
- synchronized(this){
- try {
- this.wait();
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- System.out.println("run...");
- }
-
- }
- }
- }
复制代码
老师举例的用中断线程中断处于wait状态下的线程时,上来就将wait()方法置于同步代买块下了,请问这时为什么呢?
|
|