多线程之thread、runnable的区别

参考:https://blog.csdn.net/qq_40219476/article/details/78444707

参考:https://blog.csdn.net/xdd19910505/article/details/50732328

Java 线程类:Thread,Runnable 接口

用法:
Thread:三个卖早餐的任务分给3个人
class MyThread1 extends Thread{
    private int breakfast=10;
    private String name;
    public MyThread1(String name){
        this.name=name;
    }
    public void run(){
        for(int i =0;i<500;i++){
            if(this.breakfast>0){
                System.out.println(this.name+"卖早餐---->"+(this.breakfast--));
            }
        }
    }
    public static void main(String[] args) {
        MyThread1 mt1= new MyThread1("一号窗口");
        MyThread1 mt2= new MyThread1("二号窗口");
        MyThread1 mt3= new MyThread1("三号窗口");
        mt1.start();
        mt2.start();
        mt3.start();
    }
}

Runnable:一个卖早餐的任务分给3个人

class MyThread2 implements Runnable{
    private int breakfast =10;
    private String name;
    public void run(){
        for(int i =0;i<500;i++){
            if(this.breakfast>0){
                System.out.println(Thread.currentThread().getName()+"卖早餐---->"+(this.breakfast--));
            }
        }
    }

    public static void main(String[] args) {
        //设计三个线程
        MyThread2 mt = new MyThread2();
        Thread t1 = new Thread(mt,"一号窗口");
        Thread t2 = new Thread(mt,"二号窗口");
        Thread t3 = new Thread(mt,"三号窗口");
        t1.start();
        t2.start();
        t3.start();
    }
}

 

posted @ 2018-07-16 15:29  樱圃  阅读(177)  评论(0编辑  收藏  举报