java Runnable接口如何创建线程
- java语言
- 关注:5.58K次
导语:编写多线程程序是为了实现多任务的并发执行,从而能够更好地与用户交互。下面是java Runnable接口创建线程的相关资料,欢迎阅读:
java Runnable接口创建线程
创建一个线程,最简单的方法是创建一个实现Runnable接口的类。
为了实现Runnable,一个类只需要执行一个方法调用run(),声明如下:
public void run()
你可以重写该方法,重要的是理解的run()可以调用其他方法,使用其他类,并声明变量,就像主线程一样。
在创建一个实现Runnable接口的`类之后,你可以在类中实例化一个线程对象。
Thread定义了几个构造方法,下面的这个是我们经常使用的:
Thread(Runnable threadOb,String threadName);
这里,threadOb 是一个实现Runnable 接口的类的实例,并且 threadName指定新线程的名字。
新线程创建之后,你调用它的start()方法它才会运行。
void start();
实例
下面是一个创建线程并开始让它执行的实例:
// 创建一个新的线程
class NewThread implements Runnable {
Thread t;
NewThread() {
// 创建第二个新线程
t = new Thread(this, "Demo Thread");
tln("Child thread: " + t);
t(); // 开始线程
}
// 第二个线程入口
public void run() {
try {
for(int i = 5; i > 0; i--) {
tln("Child Thread: " + i);
// 暂停线程
p(50);
}
} catch (InterruptedException e) {
tln("Child interrupted.");
}
tln("Exiting child thread.");
}
}
public class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // 创建一个新线程
try {
for(int i = 5; i > 0; i--) {
tln("Main Thread: " + i);
p(100);
}
} catch (InterruptedException e) {
tln("Main thread interrupted.");
}
tln("Main thread exiting.");
}
}
编译以上程序运行结果如下:
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
- 文章版权属于文章作者所有,转载请注明 https://xuezhezhai.com/jsj/java/nr2ez.html