java代碼-------Runnable的用法


總結:主要是實現Runnable接口就必須重寫run()方法,然后需要創建Thread類的對象,再調用start()方法

package com.s.x;

public class testRunnable implements Runnable {
	int k = 0;

	public testRunnable(int k) {
		this.k = k;
	}

	public void run() {
		int i = k;
		System.out.println();
		while (i < 30) {
			System.out.print(i + "");// 這里應該輸出的是,0,2,4,6,8……30、、偶數,它會產生空格t輸出的數字
			i += 2;
		}
		System.out.println();// 這個空格是做什么的??

	}

	public static void main(String[] args) {
		testRunnable r1 = new testRunnable(1);// 這里r1必須有參數,因為是一個帶參的構造方法
		testRunnable r2 = new testRunnable(2);// 創建兩個對象
		// 這里看,並不能調用start()方法,因為這不是線程,因為需要在run()方法
		// 你妹,我是怎么了。實現Runnable接口,就直接調用了start()方法,這個有什么用呢?即使是在run()方法里
		// 但並沒有創建線程
		// 也可以創建並啟動一個線程
		// Thread t=new Thread(r1);
		// Thread t2=new Thread(r2);
		// t.start();//總之實現Runnable接口就必須要創建Thread類的對象才能調用start()方法
		new Thread(r1).start();// 這里傳遞參數是類對象
		new Thread(r2).start();
	}
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM