- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) >
- 如何使用Java實(shí)現兩個(gè)線(xiàn)程同時(shí)運行
這篇文章給大家分享的是有關(guān)如何使用Java實(shí)現兩個(gè)線(xiàn)程同時(shí)運行的內容。小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過(guò)來(lái)看看吧。
具體如下:
/** * 兩個(gè)案例同時(shí)運行案例 * 1:這個(gè)兩個(gè)線(xiàn)程并不是有規律的運行而是有沒(méi)有規律的交替運行 */package com.test3;public class Demo10_3 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Pig pig=new Pig(10); Bird bird=new Bird(10); Thread t1=new Thread(pig); Thread t2=new Thread(bird); t1.start(); t2.start(); }}//打印class Pig implements Runnable{ int n=0; int times=0; public Pig(int n) { this.n=n; } public void run() { while(true) { try { Thread.sleep(1000); } catch (Exception e) { // TODO: handle exception } times++; System.out.println("豬說(shuō)我是一個(gè)線(xiàn)程,在輸出第"+times+"個(gè)hello, word"); if(times==n) { break; } } }}//算數學(xué)class Bird implements Runnable{ int n=0; int res=0; int times=0; public Bird(int n) { this.n=n; } public void run() { while(true) { try { Thread.sleep(1000); } catch (Exception e) { // TODO: handle exception } res+=(++times); System.out.println("鳥(niǎo)算的當前結果是"+res); if(times==n) { System.out.println("最后結果是"+res); break; } } }}
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自互聯(lián)網(wǎng)轉載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權請聯(lián)系QQ:712375056 進(jìn)行舉報,并提供相關(guān)證據,一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容。
Copyright ? 2009-2021 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 珠海市特網(wǎng)科技有限公司 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站