Java开发基础-线程-线程创建有两种方式之二[实现Runable]

  1. 单独定义线程任务的方式.

        实现Runnable接口,并重写抽象方法run来定义任务.

     下面通过简单实例演示

      任务1
class MyRunnable1 implements Runnable{

	@Override
	public void run() {
		for(int i=0;i<1000;i++){
			System.out.println("你是谁啊?");
		}	
	}	
}
      任务 2
class MyRunnable2 implements Runnable{

	@Override
	public void run() {
		for(int i=0;i<1000;i++){
			System.out.println("我是修水管的!");
		}
	}
	
}
线程测试:
public class ThreadDemo2 {

	public static void main(String[] args) {
		//实例化任务
		Runnable r1 = new MyRunnable1();
		Runnable r2 = new MyRunnable2();
		//实例化线程
		Thread t1 = new Thread(r1);
		Thread t2 = new Thread(r2);
		
		t1.start();
		t2.start();
	}
}
通过实现Runnable接口重写run方法定义线程任务,将线程与任务分离而解耦合,使线程与任务自由组合易于程序扩展。


猜你喜欢

转载自blog.csdn.net/coder_boy_/article/details/80370738