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个长和宽随机大小的矩形。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值