Java向Runnable線程傳遞參數(shù)方法實(shí)例解析
java Runnable接口:是一個(gè)接口,它里面只有一個(gè)run()方法,沒(méi)有start()方法,繼2113承Runnable并實(shí)現(xiàn)這個(gè)方法就可以實(shí)現(xiàn)多線程了,但是5261這個(gè)run()方法不能自4102己調(diào)用,必須由系統(tǒng)來(lái)調(diào)用。
向線程中傳遞數(shù)據(jù)的三種方法:
一、通過(guò)構(gòu)造函數(shù)傳遞參數(shù)
public class MyThread1 extends Thread{ private String name; public MyThread1(String name) { this.name = name; } public void run() { System.out.println('hello ' + name); } public static void main(String[] args) { Thread thread = new MyThread1('world'); thread.start(); }}
二、通過(guò)變量和方法傳遞數(shù)據(jù)
public class MyThread2 implements Runnable{ private String name; public void setName(String name) { this.name = name; } public void run() { System.out.println('hello ' + name); } public static void main(String[] args) { MyThread2 myThread = new MyThread2(); myThread.setName('world'); Thread thread = new Thread(myThread); thread.start(); }}
三、通過(guò)回調(diào)函數(shù)傳遞數(shù)據(jù)
class Data{ public int value = 0;}class Work{ public void process(Data data, Integer numbers) { for (int n : numbers) { data.value += n; } }}public class MyThread3 extends Thread{ private Work work; public MyThread3(Work work) { this.work = work; } public void run() { java.util.Random random = new java.util.Random(); Data data = new Data(); int n1 = random.nextInt(1000); int n2 = random.nextInt(2000); int n3 = random.nextInt(3000); work.process(data, n1, n2, n3); // 使用回調(diào)函數(shù) System.out.println(String.valueOf(n1) + '+' + String.valueOf(n2) + '+'+ String.valueOf(n3) + '=' + data.value); } public static void main(String[] args) { Thread thread = new MyThread3(new Work()); thread.start(); }}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. JSP之表單提交get和post的區(qū)別詳解及實(shí)例2. CSS可以做的幾個(gè)令你嘆為觀止的實(shí)例分享3. Xml簡(jiǎn)介_(kāi)動(dòng)力節(jié)點(diǎn)Java學(xué)院整理4. jsp+servlet實(shí)現(xiàn)猜數(shù)字游戲5. javascript xml xsl取值及數(shù)據(jù)修改第1/2頁(yè)6. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案7. jsp文件下載功能實(shí)現(xiàn)代碼8. 將properties文件的配置設(shè)置為整個(gè)Web應(yīng)用的全局變量實(shí)現(xiàn)方法9. ASP常用日期格式化函數(shù) FormatDate()10. JSP+Servlet實(shí)現(xiàn)文件上傳到服務(wù)器功能
