在线程的Tread对象上调用start()方法,而不是run()或者别的方法。

在调用Start方法之前,线程出于新状态中,新状态是指有一个Thread对象!但还没有一个真正的线程。

在调用start之后发生了一系列复杂的事情

启动新的执行线程(具有新的调用栈)

该线程从新状态转移到可运行状态

当该线程获得机会执行时,其目标run()方法将运行

在java中要想实现多线程,有两种手段,一种是继续Thread类,另外一种是实现Runable接口。

对于直接继承Thread的类来说,代码大致框架是:

class 类名 extends Thread{
方法1;
方法2;
…
public void run(){
// other code…
}
属性1;
属性2;
…
 
}
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 h1=new hello("A");
        hello h2=new hello("B");
        h1.start();
        h2.start();
    }

 private String name;
}

线程的运行需要本地操作系统的支持。所以需要使用start()而不是直接使用run()。

通过实现Runnable接口:

 

class 类名 implements Runnable{
方法1;
方法2;
…
public void run(){
// other code…
}
属性1;
属性2;
…
 
}
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("线程A");
        Thread demo= new Thread(h1);
        hello h2=new hello("线程B");
        Thread demo1=new Thread(h2);
        demo.start();
        demo1.start();
    }
 
    private String name;
}

【可能的运行结果】:

线程A运行     0

线程B运行     0

线程B运行     1

线程B运行     2

线程B运行     3

线程B运行     4

线程A运行     1

线程A运行     2

线程A运行     3

线程A运行     4

尽量去实现Runnable接口

posted on 2014-08-26 17:30  严zhi  阅读(6428)  评论(0编辑  收藏  举报