Java 多线程(一)

public class Test1Thread extends Thread {
    private int ticketscount = 100;
    @Override
    public void run() {

            while (true) {
            sale();
            }
    }
    //lock
    private synchronized void sale(){
        if (ticketscount > 0) {
            try {
                //sleep
                Thread.sleep(1000);
                //wakeup
                //Thread.interrupted();
            } catch (Exception e) {
                e.printStackTrace();
            }
            int curent = ticketscount--;
            System.out.println(String.format("%s卖出了第%s张票",
                    Thread.currentThread().getName(), curent));
        }
    }
}
public class TestRunable implements Runnable {
    private int ticketscount = 100;
    private Lock lock = new ReentrantLock();
    @Override
    public void run() {
        while (true){
            sale();
        }
    }
    private void sale(){
        try {
            lock.lock();
            if(ticketscount>0){
                Thread.sleep(1000);
                System.out.println(String.format("%s卖出了第%s张票",
                        Thread.currentThread().getName(),ticketscount--));
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }
}
public class TestMain {
    /**
     * 对于java程序,只要有一个前台线程在运行,这个进程就不会结束
     * 如果只有后台线程运行,进程会结束
     */

    public static void test1(){
        //创建一个资源对象
       Test1Thread test1Thread = new Test1Thread();
        //创建多个线程来竞争资源
        //线程一
       Thread thread1 = new Thread(test1Thread);
       thread1.setName("John");
        //前台线程
        thread1.setDaemon(false);
      thread1.start();
        //线程二
        Thread thread2 = new Thread(test1Thread);
        //前台线程
        thread2.setDaemon(false);
        thread2.setName("BOB");
        thread2.start();

    }
    public static void test2(){
        TestRunable runable = new TestRunable();
        new Thread(runable).start();
        new Thread(runable).start();
    }
    public static void main(String[] args){
      // test1();
       test2();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值