java中让线程停止的技巧

来源:互联网 发布:linux echo dump 编辑:程序博客网 时间:2024/05/16 15:13

/*
 * 我们的线程生命周期的控制,最好不要使用到stop、resume、suspend因为这三个方法在停止线程的运行的时候
 * 很有可能会导致死锁的问题产生
 *
 * 用下面的方法会好一些
 */
class Lesson5TestDemo1
{
 public static void main(String [] args)
 {
  ThreadControl rr = new ThreadControl();
  new Thread(rr).start();
  for(int i = 0; i < 100; i++)
  {
   if(i == 50)
   {
    rr.setFlag();
   }
   System.out.println("this main thread is runnning……");
  }
 }
}

class ThreadControl implements Runnable
{
 private boolean flag = false;
 public void setFlag()
 {
  flag = true;
 }
 public void run()
 {
  while(!flag)
  {
   System.out.println(Thread.currentThread().getName() + " is running……");
  }
 }
}

原创粉丝点击