多线程两种方式

Thread 类
Thread 类是一个具体的类,即不是抽象类,该类封装了线程的行为。要创建一个线程,程序员必须创建一个从 Thread 类导出的新类。程序员必须覆盖 Thread 的 run() 函数来完成有用的工作。用户并不直接调用此函数;而是必须调用 Thread 的 start() 函数,该函数再调用 run()。下面的代码说明了它的用法:

创建两个新线程

import java.util.*;

class TimePrinter extends Thread {
	int pauseTime;
	String name;
	public TimePrinter(int x, String n) {
		pauseTime = x;
		name = n;
	}

	public void run() {
		while(true) {
			try {
				System.out.println(name + ":" + new 
					Date(System.currentTimeMillis()));
				Thread.sleep(pauseTime);
			} catch(Exception e) {
				System.out.println(e);
			}
		}
	}

	static public void main(String args[]) {
		TimePrinter tp1 = new TimePrinter(1000, "Fast Guy");
		tp1.start();
		TimePrinter tp2 = new TimePrinter(3000, "Slow Guy");
		tp2.start();
	
	}
}

在本例中,我们可以看到一个简单的程序,它按两个不同的时间间隔(1 秒和 3 秒)在屏幕上显示当前时间。这是通过创建两个新线程来完成的,包括 main() 共三个线程。但是,因为有时要作为线程运行的类可能已经是某个类层次的一部分,所以就不能再按这种机制创建线程。虽然在同一个类中可以实现任意数量的接口,但 Java 编程语言只允许一个类有一个父类。同时,某些程序员避免从 Thread 类导出,因为它强加了类层次。对于这种情况,就要 runnable 接口

Runnable 接口
此接口只有一个函数,run(),此函数必须由实现了此接口的类实现。但是,就运行这个类而论,其语义与前一个示例稍有不同。我们可以用 runnable 接口改写前一个示例。(不同的部分用黑体表示。)

创建两个新线程而不强加类层次

import java.util.*;

class TimePrinter implements Runnable {
	int pauseTime;
	String name;
	public TimePrinter(int x, String n) {
		pauseTime = x;
		name = n;
	}

	public void run() {
		while(true) {
			try {
				System.out.println(name + ":" + new 
					Date(System.currentTimeMillis()));
				Thread.sleep(pauseTime);
			} catch(Exception e) {
				System.out.println(e);
			}
		}
	}

	static public void main(String args[]) {
		Thread t1 = new Thread(new TimePrinter(1000, "Fast Guy"));
		t1.start();
		Thread t2 = new Thread(new TimePrinter(3000, "Slow Guy"));
		t2.start();
	
	}
}

请注意,当使用 runnable 接口时,您不能直接创建所需类的对象并运行它;必须从 Thread 类的一个实例内部运行它。许多程序员更喜欢 runnable 接口,因为从 Thread 类继承会强加类层次。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值