# 線程的創建
## 線程的創建
**線程的創建有三種方式**
* **繼承Thread類**
* **實現Runnable接口**
* 實現Callable接口
>[info]可以通過實現Callable接口,重寫call()方法
常用的創建線程的方法就是繼承Thread類和實現Runable接口,第三種方法自學完善。
### 繼承Thread類
Thread是一個線程類,位于java.lang包下
**Thread類常用構造方法**
| 構造方法 | 說明 |
| :---: | :---: |
| Thread() | 創建一個線程對象 |
| Thread(String name) | 創建一個具有指定名稱的線程對象 |
| Thread(Runnable target) | 創建一個基于Runnable接口實現類的線程對象 |
| Thread(Runnable target,String name) | 創建一個基于Runnable接口實現類,并具有指定名稱的線程對象 |
**Thread類常用方法**
| 方法 | 說明 |
| :---: | :---: |
| public void run() | 線程相關的代碼寫在該方法中,一般需要重寫 |
| public void start() | 啟動線程的方法 |
| public static void sleep(long m) | 線程休眠m毫秒的方法 |
| public void join() | 優先執行調用join()方法的線程 |
**使用Thread類創建線程**
~~~
public class MyThread extends Thread {
@Override
public void run() {
System.out.println(getName() + " say:Hello,World");
}
}
//該段程序中共有兩個線程,一個是主線程,還有一個則是我們自己創建的myThread線程
//main方法是一個主線程,程序的啟動都是由main方法來啟動的,如有興趣可以了解下用戶線程和守護線程
public static void main(String[] args) {
System.out.println("主線程1");
MyThread myThread = new MyThread();
//使用start方法啟動線程,執行的是run方法中的代碼
myThread.start();
//線程是不能被多次啟動的,否則會報不合邏輯的線程錯誤
//只能啟動一次
//myThread.start();
System.out.println("主線程2");
}
輸出結果:最后的結果其實是不可預知的,因為我們不知道什么時候線程才會獲得CPU的使用權
主線程1
主線程2
Thread-0 say:Hello,World
~~~
~~~
public class MyThread extends Thread {
public MyThread(String name) {
super(name);
}
@Override
public void run() {
for(int i = 0; i < 10; i++) {
System.out.println(getName() + "線程正在循環第" + i + "次");
}
}
}
public class ThreadTest {
public static void main(String[] args) {
MyThread mtf = new MyThread("我的線程1");
mtf.start();
MyThread mts = new MyThread("我的線程2");
mts.start();
}
}
輸出結果:
隨機的結果
~~~
## 實現Runnable接口
* 只有一個方法run()
* Runnable是Java中用以實現線程的接口
* 任何實現線程功能的類都必須實現該接口
**為什么要使用Runnable接口**
* Java不支持多繼承
* 不打算重寫Thread類的其他方法
**使用Runnable創建線程**
~~~java
public class MyRunnable implements Runnable{
@Override
public void run() {
//打印該線程的當前線程名稱
System.out.println(Thread.currentThread().getName()+"say:Hello,World");
}
}
public class MyRunnableUse {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
MyRunnable myRunnable1 = new MyRunnable();
Thread thread1 = new Thread(myRunnable1);
thread1.start();
}
}
運行結果:
Thread-1say:Hello,World
Thread-0say:Hello,World
其實也是隨機的
~~~
~~~java
public class MyRunnable implements Runnable{
@Override
public void run() {
int i = 1;
while(i <= 10) {
//打印該線程的當前線程名稱
System.out.println(Thread.currentThread().getName()+"say:Hello,World" + i);
i++;
}
}
}
public class MyRunnableUse {
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
MyRunnable myRunnable1 = new MyRunnable();
Thread thread1 = new Thread(myRunnable1);
thread1.start();
}
}
~~~
>[warning]Runnable中的代碼可以被多個線程共享,適用于多個線程共享一個資源的場景