1. 程式人生 > >兩個執行緒交替列印輸出1-100

兩個執行緒交替列印輸出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();
                    }
                }
            }
        }
    }

}