java中runnable的用法解析,javarunnable解析

來源:互聯網
上載者:User

java中runnable的用法解析,javarunnable解析

1、類結構,首先有兩個類,一個是測試類別Main,一個是線程類MyThread。

2、MyThread

package com.test.thread;import java.lang.management.ThreadInfo;public class MyThread implements Runnable {String name=null;MyThread(String name){this.name=name;}@Overridepublic void run() {// TODO Auto-generated method stubwhile(true){System.out.println(name+":輸出結果...");}}}

Main

package com.test.thread;public class Main {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubMyThread mya=new MyThread("線程A");Thread testA=new Thread(mya);testA.start();MyThread myb=new MyThread("線程B");Thread testB=new Thread(myb);testB.start();}}


3、輸出結果



4、進階版

用上面的還不好說明問題,因為運行速度比較快,看不出兩者交替運行,如果線上程中假如線程休眠函數,讓線程運行一段時間就休眠,然後重新恢複會比較直觀,改動代碼如下。

package com.test.thread;import java.lang.management.ThreadInfo;public class MyThread implements Runnable {String name=null;MyThread(String name){this.name=name;}@Overridepublic void run() {// TODO Auto-generated method stubwhile(true){try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(name+":輸出結果...");}}}

5、運行結果



java中的Runnable類是什?

Runnable是Thread的介面,在大多數情況下“推薦用介面的方式”產生線程,因為介面可以實現多繼承,況且Runnable只有一個run方法,很適合繼承。

在使用Thread的時候只需要new一個執行個體出來,調用start()方法即可以啟動一個線程。
Thread Test = new Thread();
Test.start();

在使用Runnable的時候需要先new一個繼承Runnable的執行個體,之後用子類Thread調用。
Test impelements Runnable
Test t = new Test();
Thread test = new Thread(t);

在某個題目裡,需要分別列印出a與b各10次,並且每列印一次a睡1秒,列印一次b睡2秒。

可以在run方法外面定義String word與int time
之後用
Thread t1 = new Thread();
Thread t2 = new Thread();

t1.word = "a"
t1.time = 1000

t2.Word = "b"
t2.time = 2000

t1.start();
t2.start();

----Runnable的代碼

class T implements Runnable{
String s = "";
int time = 0;
public void run (){
for (int i=0;i<10;i++) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
Thread.interrupted();
}
System.out.println(s);
}
}
}
public class Test {
public static void main(String[] args) {
T t1 = new T();
T t2 = new T();
t1.s = "a";
t1.time = 100;
t2.s = "b";
t2.time = 200;
Thread a = new Thread(t1);
a.start();
Thread b = new Thread(t2);
b.start();

}
}
 
問有Java中多線程Runnable有幾種用法?

Runnable說白了只是個回調介面,並不是所有的Runnable都是用於線程的;

如果把它做為線程:
傳給Thread類
傳給Executor類
具體去看看這兩個類吧
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.