多线程运行结束后如何关闭
答案:1 悬赏:10 手机版
解决时间 2021-02-16 06:23
- 提问者网友:杀手的诗
- 2021-02-15 11:53
多线程运行结束后如何关闭
最佳答案
- 五星知识达人网友:冷風如刀
- 2019-09-22 12:34
import static java.lang.Thread.currentThread;import java.util.concurrent.TimeUnit;public class ThreadPauseDemo{ public static void main(String args[]) throws InterruptedException { Game game = new Game(); Thread t1 = new Thread(game, "T1"); t1.start(); // 现在停止Game线程 System.out.println(currentThread().getName() + " is stopping game thread"); game.stop(); // 查看Game线程停止的状态 TimeUnit.MILLISECONDS.sleep(200); System.out.println(currentThread().getName() + " is finished now"); }} class Game implements Runnable{ private volatile boolean isStopped = false; public void run(){ while(!isStopped){ System.out.println("Game thread is running......"); System.out.println("Game thread is now going to pause"); try{ Thread.sleep(200); } catch(InterruptedException e){ e.printStackTrace(); } System.out.println("Game thread is now resumed......"); } System.out.println("Game thread is stopped......"); } public void stop(){ isStopped = true; }}
程序输出如下:
Game thread is running......main is stopping game threadGame thread is now going to pauseGame thread is now resumed......Game thread is stopped......main is finished now
程序输出如下:
Game thread is running......main is stopping game threadGame thread is now going to pauseGame thread is now resumed......Game thread is stopped......main is finished now
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯