Runnable接口使用实例

Runnable接口

a.       该接口只有一个方法:public void run();

b.       实现该接口的类必须覆盖该run方法

c.       实现了Runnable接口的类并不具有任何天生的线程处理能力,这与那些从Thread类继承的类是不同的

d.       为了从一个Runnable对象产生线程,必须再单独创建一个线程对象,并把Runnable对象传递给它。

 

实例:

package com.bijian.thread;

/*
 * 图形抽象类
 */
public abstract class Shape {

	abstract void draw ();
}

 

package com.bijian.thread;

public class Rectangle extends Shape implements Runnable {
	private int w, h;

	Rectangle() {
		// Create a new Thread object that binds to this runnable and start
		// a thread that will call this runnable's run() method
		new Thread(this).start();
	}

	Rectangle(int w, int h) {
		if (w < 2)
			throw new IllegalArgumentException("w value " + w + " < 2");
		if (h < 2)
			throw new IllegalArgumentException("h value " + h + " < 2");
		this.w = w;
		this.h = h;
	}

	void draw() {
		for (int c = 0; c < w; c++)
			System.out.print('*');
		System.out.print('\n');
		for (int r = 0; r < h - 2; r++) {
			System.out.print('*');
			for (int c = 0; c < w - 2; c++)
				System.out.print(' ');
			System.out.print('*');
			System.out.print('\n');
		}
		for (int c = 0; c < w; c++)
			System.out.print('*');
		System.out.print('\n');
	}

	public void run() {
		for (int i = 0; i < 5; i++) {
			w = rnd(30);
			if (w < 2)
				w += 2;
			h = rnd(10);
			if (h < 2)
				h += 2;
			draw();
		}
	}

	int rnd(int limit) {
		// Return a random number x in the range 0 <= x < limit
		return (int) (Math.random() * limit);
	}
}

 

package com.bijian.thread;

public class RunnableDemo {

	public static void main(String[] args) {
		Rectangle r = new Rectangle(5, 6);
		r.draw();
		// Draw various rectangles with randomly-chosen widths and heights
		new Rectangle();
	}
}

 

说明:

Rectangle r = new Rectangle(5, 6);

r.draw();

这两句代码会输出一个长5*、宽6*的矩形

 

new Rectangle();

这名代码会启动Rectangle构造方法中的线程,调用此类中的run方法,循环输出5个长和宽随机大小的矩形。

 

你可能感兴趣的:(java,thread,Runnable,java多线程)