Alan's Blog

导航

java多线程

java实现多线程有两种方式:一种是继承Thread类,另外一种是实现Runnable接口

用个程序举例:

/**
 *  继承Thread类,直接调用run方法
 * */
class Hello extends Thread {
 
    public Hello () {
 
    }
 
    public Hello (String name) {
        this.name = name;
    }
 
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(name + "运行     " + i);
        }
    }
 
    public static void main(String[] args) {
        Hello h=new Hello ("A");
        h.start();
    }
 
    private String name;
}

 另外一种是实现Runnable接口

View Code
/**
 *  实现Runnable接口
 * */
class Hello implements Runnable {
 
    public Hello () {
 
    }
 
    public Hello (String name) {
        this.name = name;
    }
 
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(name + "运行     " + i);
        }
    }
 
    public static void main(String[] args) {
        Hello h1=new Hello ("线程");
        Thread th= new Thread(h1);
        th.start();
    }
 
    private String name;
}

注意main方法中,是将实例化的对象作为Thread的参数:  Hello h=new Hello ("线程");

        Thread demo1=new Thread(h);
 

关于选择继承Thread还是实现Runnable接口?

其实Thread也是实现Runnable接口的

class Thread implements Runnable {
public void run() {
        if (target != null) {
             target.run();
        }
        }
}
   
其实Thread中的run方法调用的是Runnable接口的run方法。不知道大家发现没有,Thread和Runnable都实现了run方法,这种操作模式其实就是代理模式。

posted on 2012-08-21 22:59  Alan's Blog  阅读(389)  评论(0编辑  收藏  举报