java線程之使用Runnable接口創(chuàng)建線程的方法
實現(xiàn)Runnable接口的類必須使用Thread類的實例才能創(chuàng)建線程。通過Runnable接口創(chuàng)建線程分為兩步:
1. 將實現(xiàn)Runnable接口的類實例化。
2. 建立一個Thread對象,并將第一步實例化后的對象作為參數(shù)傳入Thread類的構(gòu)造方法。
最后通過Thread類的start方法建立線程。
下面的代碼演示了如何使用Runnable接口來創(chuàng)建線程:
package mythread;
public class MyRunnable implements Runnable
{
public void run()
{
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args)
{
MyRunnable t1 = new MyRunnable();
MyRunnable t2 = new MyRunnable();
Thread thread1 = new Thread(t1, "MyThread1");
Thread thread2 = new Thread(t2);
thread2.setName("MyThread2");
thread1.start();
thread2.start();
}
}
上面代碼的運行結(jié)果如下:
MyThread1
MyThread2
相關(guān)文章
springboot+hutool批量生成二維碼壓縮導出功能
這篇文章主要介紹了springboot+hutool批量生成二維碼壓縮導出功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-10-10java線程Thread.sleep()對比對象的wait示例解析
這篇文章主要為大家介紹了java線程Thread.sleep()對比對象的wait示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-09-09詳解XML,Object,Json轉(zhuǎn)換與Xstream的使用
這篇文章主要介紹了詳解XML,Object,Json轉(zhuǎn)換與Xstream的使用的相關(guān)資料,需要的朋友可以參考下2017-02-02idea報錯:java程序包com.github.xiaoymin.knife4j.spring.annotations
這篇文章主要介紹了idea報錯:java程序包com.github.xiaoymin.knife4j.spring.annotations不存在問題解決,需要的朋友可以參考下2023-06-06mybatis實現(xiàn)mapper配置并查詢數(shù)據(jù)的思路詳解
這篇文章主要介紹了mybatis實現(xiàn)mapper配置并查詢數(shù)據(jù),本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-04-04