多線程基礎篇(一)

線程之間方法區和堆內存共享,棧內存不共享;哪一個線程調用sleep()方法,哪一個線程就進入睡眠狀態,與哪一個對象調用該方法無關.start()方法的做用是建立一個線程的棧內存,該方法與普通方法相同,執行完馬上銷燬.
多線程基礎篇(一)多線程

package test1;

public class RacerRunnable implements Runnable{
    /**
     * 龜兔賽跑多線程
     */
    public String winner;
    public void run() {
    for(int step = 1; step <= 100; step++) {
        if(Thread.currentThread().getName().equals("rabbit") && step % 10 == 0)
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        if(gameOver(step)==true) {
            break;
        }
        System.out.println(Thread.currentThread().getName()+"-->"+step );
    }
}
public boolean gameOver(int step) {
    if(winner != null) {
        return true;
    }else if(step == 100) {
        winner = Thread.currentThread().getName();
        System.out.println("winner-->"+Thread.currentThread().getName());
        return true;
    }else {
        return false;
    }
}
public static void main(String[] args) {
    RacerRunnable racer = new RacerRunnable();
    new Thread(racer, "tortoise").start();
    new Thread(racer, "rabbit").start();
    try {
        Thread.sleep(2000);   //主線程調用sleep()方法,主線程進入睡眠狀態.
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("主線程進入休眠狀態!");
}
}
相關文章
相關標籤/搜索