下面是我写的源代码:
public class InterruptThread {
public static volatile boolean isContinue = true; public static void main(String[] args) {
int interval = 1000;
new InterruptThread().new Thread1().start();
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
e.printStackTrace();
}
stopThread();
} class Thread1 extends Thread {
public void run() {
try {
int i = 1;
while (isContinue) {
Thread.sleep(1000);
// do something1 need 2 second
System.out.println(i++);
Thread.sleep(1000);
// do something2 need 2 second
System.out.println(i++);
Thread.sleep(1000);
// do something3 need 2 second
System.out.println(i++);
Thread.sleep(1000);
// do something4 need 2 second
System.out.println(i++);
Thread.sleep(1000);
// do something5 need 2 second
System.out.println(i++);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} public static void stopThread() {
isContinue = false;
}
}现在程序的运行结果是,不管我interval 设置为 1000, 2000, 3000 还是 4000,打印出来的都是1,2,3,4,5
也就是说,我所实现的程序不是马上就能让while循环停止的,一定要把本次循环运行完,才能完全停止整个while循环面试官要求我在5秒钟的任意一秒停下来,也就是说,随着interval值的不同,打印出来的值也应该不同,具体要求输出的结果如下:输入           要求打印出
1000         1
2000         1,2
3000         1,2,3
4000         1,2,3,4

解决方案 »

  1.   

    你那个肯定是不行的,因为一进入到while里面就会打印4个
    我写了一个,用的Timer与TimerTask,因为我也不熟悉这俩个类,程序也没考虑别的东西
    就只是实现一下功能,还不晓得符合要求不,希望有各位大牛也帮我看看,看看我思路是不是对的import java.util.Timer;
    import java.util.TimerTask;public class TestTimer {
    public static void main(String[] args) {
    int interval = 3000;
    Timer timer = new Timer();
    MyTimerTask timerTask = new MyTimerTask(interval);
    timer.schedule(timerTask, 0, 1000);
    }
    }class MyTimerTask extends TimerTask {
    private int i = 1;
    private int count; public MyTimerTask(int interval) {
    count = interval / 1000;
    } public void run() {
    while(count < 1) {//这里用if不行,还是搞不懂,还是有点绕不过来!
    cancel();//这里是TimerTask中的方法,task结束了,但是程序不会结束
    }
    System.out.println(i++);
    count--;
    }
    }
      

  2.   

    面试官要求我在5秒钟的任意一秒停下来,也就是说,随着interval值的不同,打印出来的值也应该不同。静候
      

  3.   

    ........
    对楼主无语了。。
    你把问题想的太复杂了!
    一秒钟打印一个数字不就行了!public void run() {
                try {
                    int i = 1;
                    while (isContinue) {
                        System.out.println(i++);
                        Thread.sleep(1000);                   
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
    自己好好看看吧...其实是很简单的事,干嘛要想那么复杂呢?
      

  4.   

    nonononono,while循环中的5个sleep仅仅是代表5个不同的长时间操作,并且所耗用的时间也不一定都是1秒
      

  5.   

    你的程序中:while (isContinue) {
                        Thread.sleep(1000);
                        // do something1 need 2 second
                        System.out.println(i++);
                        Thread.sleep(1000);
                        // do something2 need 2 second
                        System.out.println(i++);
                        Thread.sleep(1000);
                        // do something3 need 2 second
                        System.out.println(i++);
                        Thread.sleep(1000);
                        // do something4 need 2 second
                        System.out.println(i++);
                        Thread.sleep(1000);
                        // do something5 need 2 second
                        System.out.println(i++);
                    }
    因为一开始isContinue为true,它进入while循环,依次执行每条语句,它不会因为你在循环中执行了Thread.sleep(1000)后就再次检查isContinue是否为true,执行完所有语句才会再次判断循环条件,当然每次都是输出1 2 3 4 5了,改成4楼那样就ok了
      

  6.   

    中断可以用thread.interrupt或者线程池的shutdown
      

  7.   

    看的不是很明白,但是我建议使用for循环代替while循环
      

  8.   

    我现在根据lz的想法稍微改动一下public class InterruptThread {
        public static volatile boolean isContinue = true;    public static void main(String[] args) {
            int interval = 1000;
            new InterruptThread().new Thread1().start();
            try {
                Thread.sleep(interval);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            stopThread();
        }    class Thread1 extends Thread {
            public void run() {
                try {
                    int i = 1;
                    while (isContinue) {
                        // do something1 need 2 second
                        System.out.println(i++);
                        Thread.sleep(1000);
           
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }    public static void stopThread() {
            isContinue = false;
        }
    }
      

  9.   

    package threadstop;import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;public class Test { private static void test(int limit){
    Thread t = new Thread(){
    public void run(){
    int i = 0;
    while(true){
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e) {
    throw new RuntimeException(e);
    }
    System.out.println(++i);
    }
    }
    };
    t.start();
    try {
    Thread.sleep(limit);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    t.interrupt();
    }
    public static void main(String[] args) {
    test(1000);
    }
    }
      

  10.   

    唉,那个面试官大概是想故意刁难我,说不定根本就没解.
    他跟我说只要在我的基础上稍作改动即可.我当时就愣住了.
    而且我也问过他这样行不行.就是把while循环的思想抛弃,采用一个线程t,t线程用来执行执行复杂的长时间任务
    另一个线程i,i线程获得t线程的引用,并且在i线程的run()方法里执行t.interrupt方法.他说这样行是行,但不是他要的答案
    他就说只要稍作改动即可,唉....其实这个面试已经是1年前的事了,我已经工作一年了.目前有XX的打算,所以就把当年一直没搞懂
    的问题再理一遍
      

  11.   

    另外,肯定不能这样写
    while (isContinue) {
                        System.out.println(i++);
                        Thread.sleep(1000);                   
                    }
    while循环里执行的是复杂长时间的任务,比如
    while(
        doInit();     //耗时0~1秒
        doExecute();  //耗时6~8秒
        doRelease();  //耗时1~2秒
    }
      

  12.   

    public class InterruptThread {
    public static volatile boolean isContinue = true; public static void main(String[] args) {
    int interval = 4000;
    new InterruptThread().new Thread1(interval).start();
    try {
    Thread.sleep(interval);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    stopThread();
    } class Thread1 extends Thread {
    private int i = 1;
    private int count = 0; public Thread1(int interval) {
    count = interval / 1000;
    } public void run() {
    if (isContinue) {
    for (int i = 1; i <= count; i++) {
    try {
    Thread.sleep(1000);
    System.out.println(i);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }
    }
    } public static void stopThread() {
    isContinue = false;
    }
    }这样应该能满足你的要求了吧...测试了下OK的...
      

  13.   


    package my.code;public class InterruptThread {
    public static volatile boolean isContinue = true; public static void main(String[] args) {
    int interval = 3000; Thread th = new Thread() {
    public void run() {
    try {
    int i = 1;
    Thread.sleep(1000);
    // do something1 need 2 second
    System.out.println(i++);
    Thread.sleep(1000);
    // do something2 need 2 second
    System.out.println(i++);
    Thread.sleep(1000);
    // do something3 need 2 second
    System.out.println(i++);
    Thread.sleep(1000);
    // do something4 need 2 second
    System.out.println(i++);
    Thread.sleep(1000);
    // do something5 need 2 second
    System.out.println(i++);
    } catch (InterruptedException e) {
    }
    }
    };
    th.start();
    // new InterruptThread().new Thread1().start();
    try {
    Thread.sleep(interval);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    if (th.isAlive())
    th.interrupt();
    }
    }==========================
    看看这个吧,唯一的缺点就是输入3000只能打出1,2
    3001就能打出1,2,3了...嘿嘿,,,因为刚刚要打印的时候,主线程把th线程给砍掉了...
      

  14.   

    把这个线程设置成主线程的守护线程改动最小。public class InterruptThread extends Thread {
        public static volatile boolean isContinue = true;    public static void main(String[] args) {
            int interval = 3000;
            Thread thread = new Main().new Thread1();
            thread.setDaemon(true);
            thread.start();
            try {
                Thread.sleep(interval);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    //        stopThread();
        }    class Thread1 extends Thread {
            public void run() {
                try {
                    int i = 1;
                    while (isContinue) {
                        Thread.sleep(1000);
                        // do something1 need 2 second
                        System.out.println(i++);
                        Thread.sleep(1000);
                        // do something2 need 2 second
                        System.out.println(i++);
                        Thread.sleep(1000);
                        // do something3 need 2 second
                        System.out.println(i++);
                        Thread.sleep(1000);
                        // do something4 need 2 second
                        System.out.println(i++);
                        Thread.sleep(1000);
                        // do something5 need 2 second
                        System.out.println(i++);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }    public static void stopThread() {
            isContinue = false;
        }
    }新人,顺便问下,怎么调整代码格式?
      

  15.   

    thread.setDaemon(true); 
    真强!
      

  16.   

    <pre>
    都是小牛人啊
    </pre>
      

  17.   


    public class InterruptThread {
        public static volatile boolean isContinue = true;    public static void main(String[] args) {
            int interval = 1000;
            new InterruptThread().new Thread1().start();
            Thread.sleep(interval);
            stopThread();
        }    class Thread1 extends Thread {
            public void run() {
                try {
                    int i = 1;
                    while (isContinue) {
                        Thread.sleep(1000);
                        System.out.println(i++);
                     }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }    public static void stopThread() {
            isContinue = false;
        }
    }简单的使用Thread.sleep来实现时间的暂停,更高级的可以使用wait/notify机制
      

  18.   

    为什么 不用<dl class='code'>break </dl>
      

  19.   

    Thread.sleep(interval)放在main函数里面,你觉得是停止你自己写的那个线程么?唉
      

  20.   

    package com.bingo.test;public class ThreadTest {     public static volatile boolean isContinue = true;     public static void main(String[] args) {
            int interval = 1000;
            Thread t=new ThreadTest().new Thread1();
            t.start();
            try {
                Thread.sleep(interval);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            try {
    stopThread( t);
    } catch (InterruptedException e) {
    // 由于测试程序过程中用的sleep方法,仿业务处理过程,interrupt()方法调用会抛这个异常。
    e.printStackTrace();
    }
        }     class Thread1 extends Thread {
            public void run() {
                try {
                    int i = 1;
                    while (isContinue) {
                        Thread.sleep(1000);
                        // do something1 need 2 second
                        System.out.println(i++);
                        Thread.sleep(1000);
                        // do something2 need 2 second
                        System.out.println(i++);
                        Thread.sleep(1000);
                        // do something3 need 2 second
                        System.out.println(i++);
                        Thread.sleep(1000);
                        // do something4 need 2 second
                        System.out.println(i++);
                        Thread.sleep(1000);
                        // do something5 need 2 second
                        System.out.println(i++);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }     public static void stopThread(Thread t) throws InterruptedException {
            t.interrupt();         }
    }

      

  21.   


    public class InterruptThread {
        public static volatile boolean isContinue = true;    public static void main(String[] args) {
            int interval = 1000;
            new InterruptThread().new Thread1().start();
            try {
                Thread.sleep(interval);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            stopThread();
        }    class Thread1 extends Thread {
            public void run() {
                try {
                    int i = 1;
                    while (isContinue) {
                        Thread.sleep(1000);
                        // do something1 need 2 second
                        System.out.println(i++);
                        //Thread.sleep(1000);
                        // do something2 need 2 second
                        //System.out.println(i++);
                        //Thread.sleep(1000);
                        // do something3 need 2 second
                        //System.out.println(i++);
                       // Thread.sleep(1000);
                        // do something4 need 2 second
                        System.out.println(i++);
                        //Thread.sleep(1000);
                        // do something5 need 2 second
                        //System.out.println(i++);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }    public static void stopThread() {
            isContinue = false;
        }
    }
    留一行的 Thread.sleep(1000);
                        // do something1 need 2 second
                        System.out.println(i++);
    就OK了
      

  22.   


    public class InterruptThread {
    public static volatile boolean isContinue = true;
        public static void main(String []args) throws InterruptedException{
         int interval =3000;
         new InterruptThread().new Thread1().start();
         Thread.sleep(interval);
         stopThread();
    }
    class Thread1 extends Thread{
    public void run(){
    int i=1;
    while(isContinue){
    System.out.println(i);
    try {
    Thread.sleep(1000);
    i++;
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    } }
    public static void stopThread() {
        isContinue = false;
    }
    }
      

  23.   

    按楼主的说法只有在run里写一个中的线程了
      

  24.   

    public class InterruptThread {
        public static volatile boolean isContinue = true;    public static void main(String[] args) {
            int interval = 1000;
            new InterruptThread().new Thread1().start();
            try {
                Thread.sleep(interval);
                stopThread();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }    class Thread1 extends Thread {
            public void run() {
                try {
                    int taskCount = 5;
                    for (int i = 0; i < taskCount; i++) {
    // 一旦发现标志被设为停止,则退出循环
        if (!isContinue)
    break;         
               
                        Thread.sleep(1000);
                        // do something1 need 2 second
                        System.out.println(i++);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }    public static void stopThread() {
            isContinue = false;
        }
    }
    不知道LZ 是不是这个意思
    我把 WHILE 循环改成 FOR, 这样可以在任意一秒设置停止。如果WHILE则必须执行完才会去判断中止。
      

  25.   

    public class TestInterrupt {
    public static void main(String args[]) {
    Work work = new Work();
    Thread workThread = new Thread(work); Interrupt interrupt = new Interrupt(workThread);
    interrupt.setInteral(2000);
    Thread interruptThread = new Thread(interrupt); work.setTnterrupt(interruptThread);
    interruptThread.start();
    workThread.start();
    }
    }class Interrupt implements Runnable {
    public Thread thread; public int t; public Interrupt(Thread thread) {
    this.thread = thread;
    } public void setInteral(int t) {
    this.t = t;
    } public void run() {
    try {
    Thread.sleep(0);
    } catch (InterruptedException e) {
    }
    try {
    synchronized (this) {
    wait(t);
    }
    //Thread.sleep(t);
    // if (this.thread.isAlive())
    this.thread.interrupt();
    //thread.setFlag(false);
    } catch (InterruptedException e) {
    }
    }}class Work implements Runnable {
    public Thread thread = null; private boolean flag = true; public void setTnterrupt(Thread interrupt) {
    this.thread = thread;
    } public void setFlag(boolean b) {
    this.flag = b;
    } public void run() {
    if (this.thread != null)
    this.thread.notify();
    try {
    for (int i = 0; i < 5; i++) {
    if (flag) {
    Thread.sleep(1000);
    System.out.println(i);
    } else
    break;
    }
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }}
      

  26.   

    之前的 有点 小BUG, 现在已经调试好了。。
    不过针对当前应试。。还有很多细节 待大虾们来指教public class InterruptThread {
    public static volatile boolean isContinue = true; public static void main(String[] args) {

    // 设置想显示的个数
    int interval = 2;

    if(interval > 0) {

    new InterruptThread().new Thread1().start();
    try {

    Thread.sleep(interval * 1000 - 1);

    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    stopThread();
    }

    } class Thread1 extends Thread {

    public void run() {
    try {
    int taskCount = 5;

    for (int i = 0; i < taskCount; i++) {

    // 一旦发现标志被设为停止,则退出循环
    if (!isContinue)
    break; // do something1 need 2 second
    System.out.println(i + 1);

    Thread.sleep(1000);
    }
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    } public static void stopThread() {
    isContinue = false;
    }
    }
      

  27.   

    晕死...居然还没结贴.......
    public class InterruptThread {
        public static volatile boolean isContinue = true;    public static void main(String[] args) {
            int interval = 3000;        Thread th = new Thread() {
                public void run() {
                    try {
                        int i = 1;
                        Thread.sleep(1000);
                        // do something1 need 2 second
                        System.out.println(i++);
                        Thread.sleep(1000);
                        // do something2 need 2 second
                        System.out.println(i++);
                        Thread.sleep(1000);
                        // do something3 need 2 second
                        System.out.println(i++);
                        Thread.sleep(1000);
                        // do something4 need 2 second
                        System.out.println(i++);
                        Thread.sleep(1000);
                        // do something5 need 2 second
                        System.out.println(i++);
                    } catch (InterruptedException e) {
                    }
                }
            };
            th.start();
            // new InterruptThread().new Thread1().start();
            try {
                Thread.sleep(interval+1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (th.isAlive())
                th.interrupt();
        }
    }
    这样总可以了吧........
      

  28.   

    package concurrent;public class ThreadTest { /**
     * @param args
     */
    public static void main(String[] args) {
    long stopAfter = 3000;
    InteruptThread t = new InteruptThread();

    t.start();
    try {
    Thread.sleep(stopAfter);
    }catch(Exception e) {}

    // stop 和 interupt 都行。呵呵
    //t.stopThread(); 
    t.interrupt();
    } static class InteruptThread extends Thread {
    private boolean stopped = true; 
    private Object lock = new Object();
    public void run() {
    stopped = false;
    int i = 1;
    try {
    synchronized(lock) {
    while (!stopped) {
    System.out.println(i ++);
    lock.wait(1000);
    }
    }
    } catch(java.lang.InterruptedException ie) {
    return;
    }
    }

    public boolean isStopped() {
    synchronized(lock) {
    return stopped;
    }
    }

    public void stopThread() {
    synchronized(lock) {
    this.stopped = true;
    lock.notifyAll();
    }
    }
    }
    }俺来贴一个呵呵。
    献丑了。
      

  29.   

    1.Thread.interrupt()并不能阻止代码继续执行,它只是一个标记,另外在sleep这类状态的时候抛出InterruptedException 错误.2.既然要随时能停止,你为什么不在run()里面每执行完一个业务操作就检查stop标记呢?你把每个任务抽象为一个TaskHandle,每执行完一个任务就检查一下needStop标记就行了.比如:List<TaskHandle> taskList;run(){
       for(TaskHandlehandle : taskList){
           if(needStop) break;
           handle.do();       
       }
    }
    3.如果要做更精细的控制,建议你去看一下java.util.concurrent.ExecutorCompletionService类.
    这个类的api的两个例子就足够经典了.
      

  30.   

    public class test implements Runnable{
    public static int time=5000;
    public static int i=1;
    public static void main(String[] args){
    new Thread(new test()).start();
    }
    public void run(){
    long t1=System.currentTimeMillis();
    try{
    while(System.currentTimeMillis()-t1<time){
    Thread.sleep(1000);
    System.out.println(i);
    i++;
    }
    }catch(Exception e){
    e.printStackTrace();
    }
    }
    }
      

  31.   


    class InterruptThread
    {
    public static volatile boolean isContinue = true; public static void main(String[] args)
    {
    int interval = 7000;
            new InterruptThread().new Thread1().start();
            try {
                Thread.sleep(interval);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            stopThread();
    }class Thread1 extends Thread
    {
    public void run(){
    try{
    int i=1;
        while(isContinue) {
    if(i==6) //如果只有5件事要做的话,做完了我们就可从头再来了
    i=1;
    switch(i){
    case 1:Thread.sleep(1000);System.out.println(i++);break;
    case 2:Thread.sleep(1000);System.out.println(i++);break;
    case 3:Thread.sleep(1000);System.out.println(i++);break;
    case 4:Thread.sleep(1000);System.out.println(i++);break;
    case 5:Thread.sleep(1000);System.out.println(i++);break;
    default :break;
    }
    }

    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    } public static void stopThread() {
    isContinue = false;
    }
    }
    小弟刚学没多久,一点点看法
      

  32.   

    这不是很简单的事情。。public class InterruptThread { public static void main(String[] args) {
    int interval = 1000;
    Thread thread = new Thread1();
    thread.start();
    try {
    Thread.sleep(interval); } catch (InterruptedException e) {
    e.printStackTrace();
    }
    thread.interrupt();
    } static class Thread1 extends Thread {
    public void run() {
    try {
    int i = 0;
    while (!Thread.currentThread().isInterrupted()) {
    System.out.println(++i);
    Thread.sleep(1200);  //适当错开
    }
    } catch (InterruptedException e) {
    // stop thread
    }
    }
    }
    }
      

  33.   

    主要还是你的while写错了,里面有一个循环就好了你为什么要写那么多呢。把后面的都删了,在试试看。
      

  34.   

    是不是
    thread.suspend() 和 thread.resume()
      

  35.   

    为什么会骂你呢?先不说你的逻辑有问题,我最看不得程序里有重复的代码,更何况是完全相同的代码copy了5次,把后面4次去掉。
      

  36.   

    这个可能主要是考你对Thread类中的interrupt()方法,如果Thread.sleep 中的话将抛出InterruptedException,根据上面的对象try catch 的话,就直接 推出while循环.这个可能是考你对异常之类的东东吧!!