java基础之多线程四:简单案例

多线程案例:

有一个包包的数量为100个,分别从实体店和官网进行售卖。
使用多线程的方式,分别打印实体店和官网卖出包包的信息。
分别统计官网和实体店各卖出了多少个包包

第一种方法 继承Thread类:

public static void main(String[] args) {  
    //两个线程 分别为官网和实体店                      
    MyThread mt1 = new MyThread("官网");  
    MyThread mt2 = new MyThread("实体店"); 
    mt1.start();                          
    mt2.start();                                                   
}                                         

public class MyThread extends Thread {

    private static int count = 100;

    public MyThread2() {
        super();
    }

    public MyThread2(String name) {
        super(name);
    }

    @Override
    public void run() {
        int c = 0;
        while (true) {
            synchronized (MyThread.class) {
                if (count < 1) {
                    break;
                }
                System.out.println(getName() + "卖出第" + (101 - count--) + "");
                c++;
            }
        }
        System.out.println(getName() + "共卖出" + c + "");
    }
}

第二种方法 实现Runnable接口:

public static void main(String[] args) {                         
    MyRunnable mr = new MyRunnable();   
    Thread t1 = new Thread(mr,"官网");      
    Thread t2 = new Thread(mr,"实体店");     
    t1.start();                           
    t2.start();                           
}                

public class MyRunnable implements Runnable {
    private int count = 100;

    @Override
    public void run() {
        int c = 0;
        while (true) {
            synchronized (this) {
                if (count < 1) {
                    break;
                }
                System.out.println(Thread.currentThread().getName() + "卖出第" + (101 - count--) + "个");
                c++;
            }
        }
        System.out.println(Thread.currentThread().getName() + "共卖出" + c + "个");
    }
}                         

输出结果:

官网卖出第1个
官网卖出第2个
官网卖出第3个
官网卖出第4个
官网卖出第5个
实体店卖出第6个
实体店卖出第7个
实体店卖出第8个
实体店卖出第9个

...

实体店共卖出36个
官网共卖出64个

猜你喜欢

转载自www.cnblogs.com/Alex-zqzy/p/9153385.html