Runnable

在java中也可以通过实现Runnable接口的方式实现多线程,Runnable接口中指定义了一个抽象方法:、

public void  run();

【通过Runnable接口实现多线程】

class 类名称 implements Runnable{

属性...;

方法...;

  public  void  run(){  //覆写Runnable接口中的run()方法

       线程主体;  

    }

例子:

package ThreadDemo01;

class MyThread1 implements Runnable {
	private String name;

	public MyThread1(String name) {
		this.name = name;
	}

	public void run() {
		for (int i = 0; i < 10; i++) {
			System.out.println(name + "运行,i=" + i);
		}
	}
}

public class RunnableDemo01 {
	public static void main(String args[]) {
		MyThread1 mt1 = new MyThread1("线程A");// 实例化Runnable子类对象
		MyThread1 mt2 = new MyThread1("线程B");// 实例化Runnable子类对象
		Thread t1 = new Thread(mt1);// 实例化Thread类对象
		Thread t2 = new Thread(mt2);// 实例化Thread类对象
		t1.start();// 启动线程
		t2.start();
	}
}

  结果:

线程A运行,i=0
线程B运行,i=0
线程B运行,i=1
线程B运行,i=2
线程B运行,i=3
线程B运行,i=4
线程B运行,i=5
线程B运行,i=6
线程B运行,i=7
线程B运行,i=8
线程B运行,i=9
线程A运行,i=1
线程A运行,i=2
线程A运行,i=3
线程A运行,i=4
线程A运行,i=5
线程A运行,i=6
线程A运行,i=7
线程A运行,i=8
线程A运行,i=9

谁先强盗CPU就先运行谁,无论那种方式,最终都必须依靠Thread类才能启动线程。

用Thread缺点是只能单继承

Runnable接口弥补继承的缺陷,,,特性

posted on 2011-12-08 19:20  wangbokun  阅读(775)  评论(0编辑  收藏  举报

导航