java159-两个线程共同完成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();//启动线程t0
            try {
                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 );
        }
    }

运行结果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值