两个线程交替打印输出1-100

思路:声明一个全局变量int i = 1;然后将这个变量锁定,线程轮流访问这个变量,并打印即可。

package thread;

/**
 * @Title: ThreadTest1
 * @Description: TODO
 * @Author: lz
 * @CreateDate: 2018/11/6 8:58
 * @Version: 1.0
 */
public class ThreadTest1 implements Runnable{


    int i = 1;

    public static void main(String[] args) {
        ThreadTest1 t = new ThreadTest1();
        Thread t1 = new Thread(t);
        Thread t2 = new Thread(t);

        t1.setName("线程1");
        t2.setName("线程2");

        t1.start();
        t2.start();
    }

    public void run(){
        while(true){
            synchronized(this){
                notify();
                try{
                    Thread.sleep(100);
                }catch (Exception e){
                    e.printStackTrace();
                }
                if(i <= 100){
                    System.out.println(Thread.currentThread().getName()+ ":" +i);
                    i++;
                    try{
                        wait();
                    }catch (InterruptedException e ){
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}

猜你喜欢

转载自blog.csdn.net/qq_21822741/article/details/83783349
今日推荐