Java實現(xiàn)的兩個線程同時運行案例
更新時間:2019年07月22日 10:30:55 作者:To哥
這篇文章主要介紹了Java實現(xiàn)的兩個線程同時運行,涉及java多線程相關操作與使用技巧,需要的朋友可以參考下
本文實例講述了Java實現(xiàn)的兩個線程同時運行。分享給大家供大家參考,具體如下:
/** * 兩個案例同時運行案例 * 1:這個兩個線程并不是有規(guī)律的運行而是有沒有規(guī)律的交替運行 */ 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("豬說我是一個線程,在輸出第"+times+"個hello, word"); if(times==n) { break; } } } } //算數(shù)學 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("鳥算的當前結果是"+res); if(times==n) { System.out.println("最后結果是"+res); break; } } } }
運行結果:
更多java相關內容感興趣的讀者可查看本站專題:《Java進程與線程操作技巧總結》、《Java數(shù)據(jù)結構與算法教程》、《Java操作DOM節(jié)點技巧總結》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設計有所幫助。
相關文章
Java并發(fā)包工具類CountDownLatch的應用詳解
CountDownLatch是Java并發(fā)包中非常實用的一個工具類,它可以幫助我們實現(xiàn)線程之間的同步和協(xié)作。本文主要介紹了CountDownLatch的應用場景及最佳實踐,希望對大家有所幫助2023-04-04