1. 程式人生 > >多執行緒程式碼小案例

多執行緒程式碼小案例

public class TestThread {

    public static void main(String args[]) {

        RunnableEat R1 = new RunnableEat( "eat");
        Thread eat = new Thread(R1);
        eat.start();

        RunnableSleep R2 = new RunnableSleep( "sleep");
        Thread sleep = new Thread(R2);
        sleep.start();
    }
}
class RunnableEat implements Runnable {
    private String threadName;

    RunnableEat( String name) {
        threadName = name;
        System.out.println("建立執行緒eat:" +  threadName );
    }

    @Override
    public void run() {
        System.out.println("執行執行緒eat " +  threadName );
        try {
            for(int i = 4; i > 0; i--) {
                System.out.println("ThreadEat: " + threadName + ", " + i);
                // 讓執行緒睡眠一會
                Thread.sleep(50);
            }
        }catch (InterruptedException e) {
            System.out.println("Thread " +  threadName + " interrupted.");
        }
        System.out.println("Thread " +  threadName + " exiting.存在,但不執行?");
    }
}
class RunnableSleep implements Runnable {
    private String threadName;

    RunnableSleep( String name) {
        threadName = name;
        System.out.println("建立執行緒sleep" +  threadName );
    }

    @Override
    public void run() {
        System.out.println("執行執行緒sleep " +  threadName );
        try {
            for(int i = 4; i > 0; i--) {
                System.out.println("執行緒sleep睡眠: " + threadName + ", " + i);
                // 讓執行緒睡眠一會
                Thread.sleep(50);
            }
        }catch (InterruptedException e) {
            System.out.println("Thread " +  threadName + " interrupted.終止");
        }
        System.out.println("Thread " +  threadName + " exiting.存在,但不執行");
    }
}