Andy 胡

导航

JAVA·多线程:创建线程的两种方式

1.–扩展java.lang.Thread类

package multiThread;

public class Thread02extThread {

    public static void main(String[] args) {
        BoilThread boilThread = new BoilThread();
        boilThread.start();
        WashThread washThread = new WashThread();
        washThread.start();
    }
}

class BoilThread extends Thread { // 烧开水的线程
    public void run() {
        Thread tMain = Thread.currentThread();
        System.out.println("当前运行的线程是:" + tMain);

        // 假设烧水需要10秒
        try {
            System.out.println("开始烧水...");
            Thread.sleep(10000);
            System.out.println("水烧开了。");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } 
    }
}

class WashThread extends Thread { // 洗茶杯的线程
    public void run() {
        Thread tMain = Thread.currentThread();
        System.out.println("当前运行的线程是:" + tMain);
        try {
            for (int i = 1; i <= 5; i++) { // 洗5个茶杯
                System.out.print("开始洗第" + i + "个茶杯...");
                Thread.sleep(1500); // 假设每洗一个茶杯需要1.5秒
                System.out.println("第" + i + "个茶杯洗干净。");
            }
        } catch (InterruptedException ie) {
            ie.printStackTrace();
        }
    }
}

2.–实现java.lang.Runnable接口

package multiThread;
public class Thread0302impRunable {

    public static void main(String[] args) {
        降龙掌 r = new 降龙掌();
        Thread t1 = new Thread(r);
        t1.start();
        Thread t2 = new Thread(r);
        t2.start();
        Thread t3 = new Thread(r);
        t3.start();
    }
}

class Kongfu {
    public void Fight() {
        System.out.println("打人");
    }
}


class 降龙掌 extends Kongfu implements Runnable{
    @Override
    public void run() {
        super.Fight();
        System.out.println("亢龙有悔");
    }
    
}

 

posted on 2016-04-01 11:03  talkwah  阅读(240)  评论(0编辑  收藏  举报