您的位置:首页 > 编程语言 > Java开发

java创建线程常见的2种方法

2017-09-27 15:07 309 查看
在Java语言中,可以通过继承线程类Thread 或实现Runnable接口来创建用户自定义的线程,在这里主要介绍如何继承Thread类编写用户自己的线程类和如何通过实现Runnable接口来创建线程。

1.继承Thread类:

    线程Thread类是在java.lang包中定义的,但线程核心内容并非定义在这个类中,而是存在于Java平台中。实际上,这个类是真正线程的代理人,当用户操作Thread类时,Thread类将操作真正的线程,即将用户要执行的操作委托给Java平台真正的线程今昔你个处理。对于用户来说,并不需要了解Java平台如何创建和控制线程,就可以使用Thread编写线程程序,它会在线程类Thread代理下穿件出真正的线程并交付给操作系统进行调度。在这种模式下,需要注意以下两点:

    (1)编写并指定线程需要执行的方法 :   run() 方法,包含线程运行时所执行的代码

    (2)启动一个线程:   start() 方法用户启动线程

下面看一个典型的多线程示例:

public class Hthread extends Thread{

String threadName;
public Hthread(String threadName){
System.out.println("this thread name is: "+threadName);
this.threadName=threadName;
}

public void run(){
for(int i=0;i<3;i++){
try{
Thread.sleep(2000);
System.out.println("Every two seconds a print, the currentThread is: "+threadName);
}catch(InterruptedException ex){
System.err.println(ex.toString());
}
}
}

public static void main(String [] args){
System.out.println("the main start");
Hthread hthread1=new Hthread("abc");
Hthread hthread2=new Hthread("123");
hthread1.start();
hthread2.start();
System.out.println("the main end");
}

}

运行结果如下:

the main start

this thread name is: abc

this thread name is: 123

the main end

Every two seconds a print, the currentThread is: abc

Every two seconds a print, the currentThread is: 123

Every two seconds a print, the currentThread is: abc

Every two seconds a print, the currentThread is: 123

Every two seconds a print, the currentThread is: abc

Every two seconds a print, the currentThread is: 123

2.实现Runnable接口

    由于Java语言不支持多继承,一个类如果为了使用线程而继承了Thread类就不能再继承其他类,这样很难满足实际应用需要,因此Java语言提供了接口技术,通过实现一个或多个接口就能解决这个问题。

    在Java.lang包中有一个Runnable接口,该接口只有一个抽象方法void run(),用户实现线程要执行的代码。实现Runnable接口的类并不能直接作为现成运行,还需要线程类THread配合才能执行。参考示例如下:

public class Hthread implements Runnable{
String threadName;

public Hthread(String threadName){
System.out.println("this thread name is: "+threadName);
this.threadName=threadName;
}

public void run(){
for(int i=0;i<3;i++){
try{
Thread.sleep(2000);
System.out.println("the currentThread is: "+threadName);
}catch(InterruptedException ex){
System.err.println(ex.toString());
}
}
}

public static void main(String[] args){
System.out.println("the main start");
Hthread runnable1=new Hthread("abc");
Hthread runnable2=new Hthread("123");
Thread thread1=new Thread(runnable1);
Thread thread2=new Thread(runnable2);
thread1.start();
thread2.start();
System.out.println("the main end");
}

}


运行结果如下:

the main start

this thread name is: abc

this thread name is: 123

the main end

the currentThread is: abc

the currentThread is: 123

the currentThread is: 123

the currentThread is: abc

the currentThread is: 123

the currentThread is: abc
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: