经典指数          
原因
1832
浏览数
0
收藏数
 

下列有关Thread的描述,哪个是正确的?
  • 启动一个线程的方法是:thread. run()
  • 结束一个线程的通常做法是:thread. stop()
  • 将一个线程标记成daemon线程,意味着当主线程结束,并且没有其它正在运行的非daemon线程时,该daemon线程也会自动结束。
  • 让一个线程等待另一个线程的通知的方法是:thread. sleep()

     举报   纠错  
 
切换
1 个答案
C: A:thread.start() B:不建议,结束线程设置一个flag变量或者结合interrupt()方法 C:设置为后台线程 D:thread.wait() 使用一个flag变量的示例: package ThreadStop; class ThreadStopTest { public static void main(String[] args) { Thread1 t = new Thread1(); t.start(); int index = 0; while(true) { if(index++ == 500) { t.stopStop(); break; } System.out.println(Thread.currentThread().getName()); } System.out.println("main exit"); } } class Thread1 extends Thread { private boolean isStop = false; public synchronized void run() { while(!isStop) { try { wait(); //进入到对象的等待队列需要有notify方法去唤醒 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(Thread.currentThread().getName()); } } public void stopStop() { isStop = true; } } 使用interrupt()方法 package ThreadStop; class ThreadStopTest { public static void main(String[] args) { Thread1 t = new Thread1(); t.start(); int index = 0; while(true) { if(index++ == 500) { t.stopStop(); //终端t的线程,此时就会抛出异常 t.interrupt(); break; } System.out.println(Thread.currentThread().getName()); } System.out.println("main exit"); } } class Thread1 extends Thread { private boolean isStop = false; public synchronized void run() { while(!isStop) { try { wait(); //进入到对象的等待队列需要有notify方法去唤醒 } catch (InterruptedException e) { e.printStackTrace(); if(isStop) return; } System.out.println(Thread.currentThread().getName()); } } public void stopStop() { isStop = true; } }
 
切换
撰写答案
扫描后移动端查看本题