多线程基础篇(一)

线程之间方法区和堆内存共享,栈内存不共享;哪个线程调用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("主线程进入休眠状态!");
}
}

猜你喜欢

转载自blog.51cto.com/14472348/2486608
今日推荐