首页 > 技术文章 > Java进阶知识查漏补缺02

cuijunfeng 2020-07-01 23:45 原文

通过继承Thread方式创建线程后处理共享资源问题:

package com.cjf.Thread;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Author: Everything
 * Date: 2020-07-01
 * Time: 16:23
 */

class Window extends Thread{
    //此时必须引入静态,让三个线程实例共用一个变量
    //一提到共享问题,就要想到静态
    private static int ticket=100;

    @Override
    public void run() {
        while (true){
            if (ticket > 0){
                ticket--;
                System.out.println(Thread.currentThread().getName()+"售出车票,余票为"+ticket);

            }else {
                break;
            }
        }
    }
}




public class WindowTest {
    public static void main(String[] args) {
        Window window1 = new Window();
        Window window2 = new Window();
        Window window3 = new Window();
        window1.setName("售票窗口一");
        window2.setName("售票窗口二");
        window3.setName("售票窗口三");
        window1.start();
        window2.start();
        window3.start();
    }

}

 

通过实现Runnable接口方式创建线程后处理共享资源问题:

package com.cjf.Thread;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * Author: Everything
 * Date: 2020-07-01
 * Time: 17:07
 */


class Window2 implements Runnable{

    private  int ticket=100;
    @Override
    public void run() {
        while (true){
            if (ticket > 0){
                ticket--;
                System.out.println(Thread.currentThread().getName()+"售出车票,余票为"+ticket);

            }else {
                break;
            }
        }
    }
    }

public class WindowTest1 {
    public static void main(String[] args) {
        Window2 window21 = new Window2();
        Thread thread1 = new Thread(window21);
        Thread thread2 = new Thread(window21);
        Thread thread3 = new Thread(window21);
        thread1.setName("一号售票口");
        thread2.setName("二号售票口");
        thread3.setName("三号售票口");
        thread1.start();
        thread2.start();
        thread3.start();


    }
}

 

推荐阅读