启动线程的方法

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

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

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

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

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

当该线程得到机会执行时,其目标run()方法将运行操作系统

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

对于直接继承Thread的类来讲,代码大体框架是:code

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接口:blog

 

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接口

相关文章
相关标签/搜索