多线程两个线程轮流打印数字,一直到100

package com.hp.zuoye;

public class ThreaDemo extends Thread{
    public static int count=0;
    public static Object object=new Object();
    @Override
    public void run() {

            try {
                while (true){
                    Thread.sleep(2000);
                    synchronized (object){
                    if (count<100){
                        System.out.println(count);
                        count++;
                    }else {
                        System.out.println("打印完成");
                        System.exit(0);
                    }

                }
            }


        } catch (InterruptedException e) {
                e.printStackTrace();
            }


    }

    public static void main(String[] args) {
        ThreaDemo td1=new  ThreaDemo();
        ThreaDemo td2=new ThreaDemo();
        Thread thread1=new Thread(td1);
        Thread thread2=new Thread(td2);
        thread1.start();
        thread2.start();
    }
}

你可能感兴趣的:(线程)