多线程Thread和Runnable的实现
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