线程入门-使用Thread类
2019獨角獸企業重金招聘Python工程師標準>>>
?
發射倒計時程序:
/*** Created by Administrator on 2017/8/31.*/ public class LiftOff implements Runnable {protected int countDown = 10;private static int taskCount = 0;private final int id = taskCount++;public LiftOff() {}public LiftOff(int countDown) {this.countDown = countDown;}public String status() {return "#" + id + "(" +(countDown > 0 ? countDown : "LiftOff!") + ")";}@Overridepublic void run() {while (countDown-- > 0) {System.out.print(status());Thread.yield();}}}如何驅動
示例1:
在下面的示例中,這個任務的run()不是由單獨的線程驅動的,它是在main()中直接調用的
/*** Created by Administrator on 2017/8/31.*/ public class MainThread {public static void main(String[] args) {LiftOff launch = new LiftOff();launch.run();System.out.println("等待發射\r\n");} }輸出結果:
總結:當從runnable導出一個類時,它必須具有run()方法,但是這個方法并無特殊之處,它不會產生任何內在的線程能力。要實現線程行為,你必須顯式地將一個任務附著到線程上。
示例二:
/*** Created by Administrator on 2017/8/31.*/ public class MainThread {public static void main(String[] args) {/* LiftOff launch = new LiftOff();launch.run();System.out.println("\r\n等待發射\r\n");*/Thread t = new Thread(new LiftOff());t.start();System.out.println("等待發射!");} }輸出結果:
總結:將Runnable對象轉變為工作任務的傳統方式是把它提交給一個Thread構造器,start()起新線程,run在新起線程中啟動該任務。
盡管start()看起來是產生了一個對長期運行方法的調用,但是從輸出中可以看到,start()迅速地返回了,因為“等待發射!"消息在倒計時完成之前就出現了。實際上,你產生的是對LiftOff.run()的方法調用,并且這個方法還沒有完成,但是因為LiftOff.run()是由不同的線程執行的,因此你仍舊可以執行main()線程中的其他操作,因些程序會同時運行2個方法,main()和LiftOff.run()是程序中與其他線程”同時“執行的代碼。
示例三:
添加更多的線程
/*** Created by Administrator on 2017/8/31.*/ public class MainThread {public static void main(String[] args) {for (int i = 0; i < 5; i++) {new Thread(new LiftOff()).start();}System.out.print("等待發射\r\n");} }輸出:每次執行結果不惟一
結論:輸出說明不同的任務的執行在線程被換進換出時混在了一起。這種交換是由線程調度器自動控制的。
轉載于:https://my.oschina.net/u/560971/blog/1527075
總結
以上是生活随笔為你收集整理的线程入门-使用Thread类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SSO 单点登录解决方案
- 下一篇: linux安装mysql5.7.19