解决重复调用一个线程内某个方法的问题

目的是重复调用method()方法:

package commandlist;

public class MyThread extends Thread {

    public static boolean flag=true;
    @Override
    public void run() {
        super.run();
        method();
        while(true){

            while(flag){
                if(this.interrupted()){
                    throw new RuntimeException();
                }
            }
            method();
        }
    }

    public void method(){
      for(int i=1;i<10;i++){
          System.out.println(Thread.currentThread().getName()+":"+i);
      }
    }
}

测试类:

package commandlist;

public class TestThread {
    public static void main(String[] args) {

        MyThread thread=new MyThread();
        thread.start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        MyThread.flag=false;
        //MyThread.flag=true;

        System.out.println(thread.isAlive());
        System.out.println(thread.isInterrupted());
        //判断当前线程的线程组中活动线程的数目,为1时其他线程运行完毕
        System.out.println(Thread.activeCount());
        //java.lang.IllegalThreadStateException
        //thread.start();
        //这是主线程调用
       // thread.run();

    }
}

 

你可能感兴趣的:(多线程与并发)