![](https://img-blog.csdnimg.cn/d6da08780db9400abd9c8a572cee1560.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA6I-c5Y-I5a2m,size_20,color_FFFFFF,t_70,g_se,x_16)
创建一个线程
Java 提供了三种创建线程的方法:
通过实现 Runnable 接口;
通过继承 Thread 类本身;
通过 Callable 和 Future 创建线程。
为了实现 Runnable,一个类只需要执行一个方法调用 run(),声明如下:
public void run()
Thread 定义了几个构造方法,下面的这个是我们经常使用的:
Thread(Runnable threadOb, String threadName);
threadOb 是一个实现 Runnable 接口的类的实例,并且 threadName 指定新线程的名字。
新线程创建之后,调用它的 start() 方法它才会运行。
void start();
RunnableDemo.java
public class RunnableDemo implements Runnable {
private Thread t;
private String threadName;
public RunnableDemo(String name) {
threadName = name;
System.out.println("Creating ========this " + threadName );
}
@Override
public void run() {
System.out.println("Running1=======run1 " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread-----run2: " + threadName + ", " + i);
// 让线程睡眠一会
Thread.sleep(50);
}
}catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread========run3 " + threadName + " exiting.");
}
public void start () {
System.out.println("Starting-----start " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}
Test.java
public class Test
{
public static void main(String args[]) {
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();
RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2.start();
}
}
运行结果:
![](https://img-blog.csdnimg.cn/1c0f0527d4ac477aa7c04afca2e6f2ee.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA6I-c5Y-I5a2m,size_12,color_FFFFFF,t_70,g_se,x_16)