Java線程基本使用之如何實現(xiàn)Runnable接口
更新時間:2024年01月16日 10:05:01 作者:兮動人
這篇文章主要介紹了Java線程基本使用之如何實現(xiàn)Runnable接口問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
1. 實現(xiàn) Runnable 接口
說明
- java是單繼承的,在某些情況下一個類可能已經(jīng)繼承了某個父類,這時在用繼承Thread類方法來創(chuàng)建線程顯然不可能了。
- java設計者們提供了另外一個方式創(chuàng)建線程,就是通過實現(xiàn)Runnable接口來創(chuàng)建線程
應用案例
- 請編寫程序,該程序可以每隔
1
秒。在控制臺輸出“你好,兮動人”,當輸出10
次后,自動退出。 - 使用實現(xiàn)
Runnable
接口的方式實現(xiàn)。
public class Thread02 { public static void main(String[] args) { Dog dog = new Dog(); //dog.start(); //這里不能調(diào)用 start 方法 //創(chuàng)建了 Thread 對象,把 dog 對象(實現(xiàn)了 Runnable ),放入了 Thread Thread thread = new Thread(dog); thread.start(); } } class Dog implements Runnable { //通過實現(xiàn)Runnable接口來實現(xiàn) int count = 0; @Override public void run() { //普通方法 while (true) { System.out.println("你好,兮動人-" + (++count) + Thread.currentThread().getName()); //休眠1秒 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } if (count == 10) { break; } } } }
這里底層使用了設計模式【代理模式】=> 代碼模擬實現(xiàn)Runnable
接口 開發(fā)線程的機制。
public class Thread02 { public static void main(String[] args) { Tiger tiger = new Tiger(); ThreadProxy threadProxy = new ThreadProxy(tiger); threadProxy.start(); } } class Animal {} class Tiger extends Animal implements Runnable { @Override public void run() { System.out.println("老虎..."); } } //線程代理類,模擬了一個極簡的Thread類 class ThreadProxy implements Runnable { //可以把 Proxy 類當做 Thread private Runnable target = null; // 屬性類型 是 Runnable @Override public void run() { if (target != null) { target.run();//動態(tài)綁定(運行類型是Tiger) } } public ThreadProxy(Runnable target) { this.target = target; } public void start() { start0();//這個方法是真正實現(xiàn)多線程的方法 } public void start0() { run(); } }
2. 線程使用應用案例–多線程執(zhí)行
請編寫一個程序,創(chuàng)建兩個線程,一個線程每隔1
秒輸出“hello,world
”,輸出10
次,退出,另一個線程每隔1
秒輸出“hi
”,輸出5
次退出。
public class Thread03 { public static void main(String[] args) { T1 t1 = new T1(); T2 t2 = new T2(); Thread thread1 = new Thread(t1); thread1.start(); Thread thread2 = new Thread(t2); thread2.start(); } } class T1 implements Runnable { int count = 0; @Override public void run() { while (true) { System.out.println("hello world" + (++count)); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } if (count == 10) { break; } } } } class T2 implements Runnable { int count = 0; @Override public void run() { while (true) { System.out.println("hi" + (++count)); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } if (count == 5) { break; } } } }
3. 如何理解線程
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
mybatis plus 開啟sql日志打印的方法小結(jié)
Mybatis-Plus(簡稱MP)是一個 Mybatis 的增強工具,在 Mybatis 的基礎上只做增強不做改變,為簡化開發(fā)、提高效率而生。本文重點給大家介紹mybatis plus 開啟sql日志打印的方法小結(jié),感興趣的朋友一起看看吧2021-09-09