java学习(159):两个线程共同完成1到100计算
生活随笔
收集整理的這篇文章主要介紹了
java学习(159):两个线程共同完成1到100计算
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
//利用兩個線程實現1到100的計算
public class MyRannable implements java.lang.Runnable{private Thread th_0;private Thread th_2;int sum=0;//存儲累加和的結果int i=1;public void run(){String thName=Thread.currentThread().getName();//獲取當前線程的名字while (i<=101){System.out.println( "當前線程"+thName+"正在計算" );System.out.println( "當前的累加和" +sum);sum+=i++;if(i==50&&thName.equals( "線程1" )){break;}try {Thread.sleep( 100 );}catch (InterruptedException e){e.printStackTrace();}}}public MyRannable(Thread t0,Thread t2){if(t0==null){th_0=new Thread( this );//th0和th2共享一個實現runnable的實例}if(t2==null){th_2=new Thread( this );}th_0.setName( "線程1" );th_2.setName( "線程2" );th_0.start();//啟動線程t0try {th_0.join();}catch (InterruptedException e){e.printStackTrace();}th_2.start();}
}
測試類
public class test106 {public static void main(String[] args){//Thread t0=new Thread( );//t0.setName( "線程1" );//Thread t2=new Thread( );//t2.setName( "線程2" );Thread t0=null;Thread t2=null;MyRannable ran=new MyRannable( t0,t2 );} }運行結果
總結
以上是生活随笔為你收集整理的java学习(159):两个线程共同完成1到100计算的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux git删除的文件怎么还原,从
- 下一篇: vb开发需要的软件