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();
	}
}

  

原文地址:https://www.cnblogs.com/langlove/p/3488222.html