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 );
        }
    }

运行结果

 

posted @   前端导师歌谣  阅读(214)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
点击右上角即可分享
微信分享提示