Java实现多线程的方式有三种
1、传统方式,通过继承Thread类
2、通过实现Runnable接口,然后建对象传递到new Thread(Runnable)中,启动线程
3、使用ExecutorService、Callable、Future实现有返回结果的多线程

今天,我只说通过接口Runnable的方式实现多线程的案例,PS:这玩意过几天就忘了。。。蛋疼

实现多线程买票案例

案例中,通过实现Runnable接口,然后传递票的张数,每次买票后,设定休眠100ms,这个地方,我还设置了VIP的窗口,通过Thread的setPriority方法,设定线程的优先级,线程的优先级 1-10 1 是最小的, 10 是优先级最高的,用的锁是这个实例化对象本身

package com.yellowcong.thread.tickt;

public class TicktRunnable implements Runnable{

    //票的张数
    private int count ;

    public TicktRunnable(int count) {
        super();
        this.count = count;
    }


    @Override
    public void run() {
        //这个类的自身
        while(true){
            sell();
        }
    }

    /**
     * 在run里面写上了这个本类的synchronized 后,不释放锁
     */
    public synchronized void sell(){
        if(count > 0){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            count -- ;
            System.out.printf("%s购买的票,剩余票%d\r",Thread.currentThread().getName(),count);

        }else{
            System.out.println("票已经售完");
            Thread.currentThread().stop();
        }
    }

}

测试类

启动了4个用户,来进行买票操作

package com.yellowcong.thread.tickt;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TicketTest {


    public static void main(String[] args) {


        TicktRunnable tickt = new TicktRunnable(100);

        new Thread(tickt,"用户1").start();
        new Thread(tickt,"用户2").start();
        new Thread(tickt,"用户3").start();
        new Thread(tickt,"用户4").start();

        Thread thread1 = new Thread(tickt,"VIP用户");
        //设置线程的优先级 1-10  1 是最小的, 10 是优先级最高的
        thread1.setPriority(10);
        thread1.start();


         ExecutorService executor = Executors.newFixedThreadPool(5);
         for(int i =0;i<5;i++){
             executor.execute(tickt);
         }

         while(executor.isTerminated()){
             executor.shutdown();
             System.out.println("执行完毕");
         }


    }
}