日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

线程入门-使用Thread类

發布時間:2024/4/17 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 线程入门-使用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类的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。