Java 多线程练习---创建两个子线程,每个线程交替输出“你好--来自线程***”...
生活随笔
收集整理的這篇文章主要介紹了
Java 多线程练习---创建两个子线程,每个线程交替输出“你好--来自线程***”...
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
|--需求說(shuō)明
|--實(shí)現(xiàn)思路
1、創(chuàng)建一個(gè)類,實(shí)現(xiàn)Runnable,在這個(gè)類里面重寫(xiě)run()方法,在run()方法里面寫(xiě)一個(gè)20的for循環(huán)
2、創(chuàng)建一個(gè)類,實(shí)例化上面的類,用這個(gè)類的對(duì)象創(chuàng)建線程
?
|--代碼內(nèi)容
1 package cn.thread; 2 3 /** 4 * @auther::9527 5 * @Description: 6 * @program: shi_yong 7 * @create: 2019-08-05 08:57 8 */ 9 public class CommonThread implements Runnable { 10 //重寫(xiě)run方法 11 @Override 12 public void run() { 13 for (int i = 0; i <20 ; i++) { 14 //獲取當(dāng)前線程名稱 15 Thread t = Thread.currentThread(); 16 //按需求生成輸出語(yǔ)句 17 System.out.println(i+"你好,來(lái)自線程"+t.getName()); 18 } 19 } 20 } 生成輸出需求的類 1 package cn.thread; 2 3 /** 4 * @auther::9527 5 * @Description: 多線程 6 * @program: shi_yong 7 * @create: 2019-08-05 08:51 8 */ 9 public class Demo1 { 10 public static void main(String[] args) { 11 //實(shí)例化需要運(yùn)行的類 12 CommonThread ct = new CommonThread(); 13 //創(chuàng)建線程 14 Thread t2 = new Thread(ct); 15 Thread t1 = new Thread(ct); 16 //啟動(dòng)線程 17 t1.start(); 18 t2.start(); 19 } 20 } 程序入口?
|--運(yùn)行結(jié)果
?
轉(zhuǎn)載于:https://www.cnblogs.com/twuxian/p/11302812.html
總結(jié)
以上是生活随笔為你收集整理的Java 多线程练习---创建两个子线程,每个线程交替输出“你好--来自线程***”...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 使用EasyExcel读取excel文件
- 下一篇: Java技术:Mybatis-plus常