本文實例講述了Java實現的兩個線程同時運行。分享給大家供大家參考,具體如下:
/**
* 兩個案例同時運行案例
* 1:這個兩個線程并不是有規律的運行而是有沒有規律的交替運行
*/
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;
}
}
}
}
//算數學
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數據結構與算法教程》、《Java操作DOM節點技巧總結》、《Java文件與目錄操作技巧匯總》和《Java緩存操作技巧匯總》
希望本文所述對大家java程序設計有所幫助。