Runnable和Thread

时间:2020-10-05 22:16:36   收藏:0   阅读:30

继承Thread类

实现Runnable接口

package DemoThread;
//多个线程同时操作同一个对象
//买火车票的例子
public class TestThread02 implements Runnable{
    //票数
    private int ticketNums=10;

    @Override
    public void run() {
        while (true) {
            if(ticketNums<=0){
                break;
            }
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "-->拿到了第" + ticketNums-- + "票");
        }
        }

    public static void main(String[] args) {
        TestThread02 testThread02=new TestThread02();
        new Thread(testThread02,"阿优").start();
        new Thread(testThread02,"大黄").start();
        new Thread(testThread02,"小柔").start();

    }


}

技术图片

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!