Java 多线程的实现方法

package com.jckb;
/**多线程实现的两种方法
 * 
 * @author gx
 *
 */

public class Test2 {
    public static void main(String[] args) {
        Mythread m = new Mythread();
        m.start();// 不能直接调用run方法
        // m.run();//是方法调用,不是线程的启动
        Thread t = new Thread(new Mythread2());
        t.start();

    }
}

// 线程停止的方法是run方法返回
// flag=false退出
// 线程停止后不能再次启动
class Mythread extends Thread {
    @Override
    public void run() {
        boolean flag = true;
        int i = 1;
        while (flag) {

            System.out.println("i=" + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            i++;
            if (i == 5) {
                flag = false;
                // return;
            }
        }
    }
}

class Mythread2 implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("i=" + i);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

posted @ 2017-01-01 18:28  郭鑫  阅读(174)  评论(0编辑  收藏  举报