• 线程之Thread和Runnable


    Runnable:

    public class threadTest implements  Runnable{

    private AtomicInteger tickets = new AtomicInteger(3);
    public void run() {
    int ticketNum ;
    while((ticketNum = tickets.getAndDecrement())>0)
    {
    System.out.println(Thread.currentThread().getName()+" "+ticketNum);
    }
    }
    public class Test {
    public static void main(String[] args)
    {
    threadTest t = new threadTest();
    new Thread(t).start();
    new Thread(t).start();
    }
    }
    其中一次的结果为:

    Thread-0 3
    Thread-1 2
    Thread-0 1

    Thread:

    public class threadTest extends Thread{

    private AtomicInteger tickets = new AtomicInteger(3);
    public void run() {
    int ticketNum ;
    while((ticketNum = tickets.getAndDecrement())>0)
    {
    System.out.println(Thread.currentThread().getName()+" "+ticketNum);
    }
    }
    public class Test {
    public static void main(String[] args)
    {
    new threadTest().start();
    new threadTest().start();
    }
    }
    其中一次结果:

    Thread-1 3
    Thread-0 3
    Thread-1 2
    Thread-0 2
    Thread-1 1
    Thread-0 1

    在网上有看到说通过Runnable实现的线程能够共享资源,而继承Thread的线程不能共享资源。这个例子是说明这个问题吗?

  • 相关阅读:
    协程方法的开启、关闭以及传参
    五种访问修饰符
    多态之虚方法、抽象类、接口
    递归算法
    继承之构造方法
    鼠标相关操作(Cursor类及相关API)
    遇到的问题(七)
    遇见的问题(六)
    遇见的问题(五)
    函数VS对象
  • 原文地址:https://www.cnblogs.com/moxia1234/p/11397827.html
Copyright © 2020-2023  润新知