Java在不同執行緒中執行程式碼

FrankYou發表於2017-03-08

start()方法開始為一個執行緒分配CPU時間,這導致對run()方法的呼叫。

 

程式碼1

package Threads;

/**
 * Created by Frank
 */
public class ThreadsDemo1 extends Thread {
    private String msg;
    private int count;

    public ThreadsDemo1(final String msg, int n) {
        this.msg = msg;
        count = n;
        setName(msg + " runner Thread");
    }

    public void run() {
        while (count-- > 0) {
            System.out.println(msg);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                return;
            }
        }
        System.out.println(msg + " all done.");
    }

    public static void main(String[] args) {
        new ThreadsDemo1("Hello from X", 10).start();
        new ThreadsDemo1("Hello from Y", 15).start();
    }
}

程式碼2:

package Threads;

/**
 * Created by Frank
 */
public class ThreadsDemo2 implements Runnable {
    private String msg;
    private Thread t;
    private int count;

    public static void main(String[] args) {
        new ThreadsDemo2("Hello from X", 10);
        new ThreadsDemo2("Hello from Y", 15);
    }

    public ThreadsDemo2(String m, int n) {
        this.msg = m;
        count = n;
        t = new Thread(this);
        t.setName(msg + "runner Thread");
        t.start();
    }

    @Override
    public void run() {
        while (count-- > 0) {
            System.out.println(msg);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                return;
            }
        }
        System.out.println(msg + " all done.");
    }
}

程式碼3:

package Threads;

/**
 * Created by Frank
 */
public class ThreadsDemo3 {
    private int count;

    public static void main(String[] args) {
        new ThreadsDemo3("Hello from X", 10);
        new ThreadsDemo3("Hello from Y", 15);
    }
    public ThreadsDemo3(final String msg, int n) {
        this.count = n;
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                while (count-- > 0) {
                    System.out.println(msg);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        return;
                    }
                }
                System.out.println(msg + " all done.");
            }
        });
        t.setName(msg + " runner Thread");
        t.start();
    }
}

 

相關文章