62,628
社区成员
发帖
与我相关
我的任务
分享
public static void main(String[] args)
{
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.execute(new Runnable()
{
@Override
public void run()
{
try
{
TimeUnit.SECONDS.sleep(10);
System.out.println("first run over");
}
catch (InterruptedException e)
{
System.out.println("first interrupted!!!");
}
System.out.println("----分割线执行----");
try
{
TimeUnit.SECONDS.sleep(5);
System.out.println("second run over");
}
catch (InterruptedException e)
{
System.out.println("second interrupted!!!");
}
}
});
executor.shutdownNow();
}
public class HH
{
public static void main(String[] args) throws InterruptedException
{
ThreadA ta = new ThreadA();
ta.setName("ThreadA");
ta.start();
Thread.sleep(2000);
System.out.println(ta.getName() + "正在被中断...");
ta.interrupt();
System.out.println("ta.isInterrupted()=" + ta.isInterrupted());
}
}
class ThreadA extends Thread
{
int count = 0;
public void run()
{
System.out.println(getName() + "将要运行...");
while (!this.isInterrupted())
{
try
{
Thread.sleep(400);
}
catch (InterruptedException e)
{
System.out.println(getName() + "****从阻塞中退出...");
System.out.println("this.isInterrupted()=" + this.isInterrupted());
}
try
{
System.out.println(getName() + "运行中" + count++);
Thread.sleep(400);
}
catch (InterruptedException e)
{
System.out.println(getName() + "---------从阻塞中退出...");
System.out.println("this.isInterrupted()=" + this.isInterrupted());
}
}
System.out.println(getName() + "已经终止!");
}
}
神奇了
ThreadA将要运行...
ThreadA运行中0
ThreadA运行中1
ThreadA正在被中断...
ta.isInterrupted()=true
ThreadA****从阻塞中退出...
this.isInterrupted()=false
ThreadA运行中2
ThreadA运行中3
ThreadA运行中4
ThreadA运行中5
ThreadA运行中6
ThreadA运行中7
ThreadA运行中8
ThreadA运行中9
...