JAVA多线程Thread和Runnable的实现
java中只允许单一继承,但允许实现多个接口,因此第二种方法更灵活。
/**
* 运行继承java.lang.thread类定义的线程
*/
public void startone() {
// 创建实例
onethread onethread = new onethread();
// 启动线程threada
onethread.startthreada();
try {
// 设置线程休眠1秒
thread.sleep(1000);
} catch (interruptedexception e) {
e.printstacktrace();
}
// 停止线程,此处为什么不用stop()方法,因为该方法已经废弃,但可以用在死锁。
onethread.stopthreada();
}
/**
* 运行实现runnable接口定义的线程
*/
public void starttwo() {
// 创建实例
runnable runnable = new twothread();
// 将实例放入到线程中
thread threadb = new thread(runnable);
// 启动线程
threadb.start();
}
// 继承thread类定义线程
class onethread extends thread {
private boolean running = false;
public void start() {
this.running = true;
super.start();
}
public void run() {
int i = 0;
try {
while (running) {
system.out.println("继承thread类定义线程程序体......" + i++);
thread.sleep(200);
}
} catch (interruptedexception e) {
e.printstacktrace();
}
}
public void startthreada() {
system.out.println("启动继承thread类定义线程");
this.start();
}
public void stopthreada() {
system.out.println("关闭继承thread类定义线程");
this.running = false;
}
}
// 实现runnable接口定义线程
class twothread implements runnable {
private date rundate;
public void run() {
system.out.println("实现runnable接口定义线程程序体......");
this.rundate = new date();
system.out.println("线程启动时间......" + rundate);
}
public static void main(string[] args) {
// 实例化对象
threadstartandstop threadstartandstop = new threadstartandstop();
threadstartandstop.startone();
threadstartandstop.starttwo();
}
启动继承thread类定义线程
继承thread类定义线程程序体......0
继承thread类定义线程程序体......1
继承thread类定义线程程序体......2
继承thread类定义线程程序体......3
继承thread类定义线程程序体......4
关闭继承thread类定义线程
实现runnable接口定义线程程序体......
线程启动时间......fri mar 15 12:56:57 cst 2013