服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - java Runnable接口创建线程

java Runnable接口创建线程

2020-11-27 10:41duruiqi_fx Java教程

这篇文章主要介绍了java Runnable接口创建线程的相关资料,需要的朋友可以参考下

java Runnable接口创建线程

创建一个线程,最简单的方法是创建一个实现Runnable接口的类。

为了实现Runnable,一个类只需要执行一个方法调用run(),声明如下:

?
1
public void run()

你可以重写该方法,重要的是理解的run()可以调用其他方法,使用其他类,并声明变量,就像主线程一样。

在创建一个实现Runnable接口的类之后,你可以在类中实例化一个线程对象。

Thread定义了几个构造方法,下面的这个是我们经常使用的:

?
1
Thread(Runnable threadOb,String threadName);

这里,threadOb 是一个实现Runnable 接口的类的实例,并且 threadName指定新线程的名字。
新线程创建之后,你调用它的start()方法它才会运行。

?
1
void start();

实例

下面是一个创建线程并开始让它执行的实例:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// 创建一个新的线程
class NewThread implements Runnable {
  Thread t;
  NewThread() {
   // 创建第二个新线程
   t = new Thread(this, "Demo Thread");
   System.out.println("Child thread: " + t);
   t.start(); // 开始线程
  }
 
  // 第二个线程入口
  public void run() {
   try {
     for(int i = 5; i > 0; i--) {
      System.out.println("Child Thread: " + i);
      // 暂停线程
      Thread.sleep(50);
     }
   } catch (InterruptedException e) {
     System.out.println("Child interrupted.");
   }
   System.out.println("Exiting child thread.");
  }
}
 
public class ThreadDemo {
  public static void main(String args[]) {
   new NewThread(); // 创建一个新线程
   try {
     for(int i = 5; i > 0; i--) {
      System.out.println("Main Thread: " + i);
      Thread.sleep(100);
     }
   } catch (InterruptedException e) {
     System.out.println("Main thread interrupted.");
   }
   System.out.println("Main thread exiting.");
  }
}

编译以上程序运行结果如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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.

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

原文链接:http://blog.csdn.net/duruiqi_fx/article/details/52187275

延伸 · 阅读

精彩推荐