zoukankan      html  css  js  c++  java
  • 线程之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的线程不能共享资源。这个例子是说明这个问题吗?

  • 相关阅读:
    第六章 函数与宏定义实验
    第五章 循环结构实验
    第五章 循环结构课内反思
    第四章 分支结构实验
    C程序设计实验报告
    509寝室小组
    第九章 构造数据类型实验
    第八次实验报告
    数组实验
    函数与宏定义实验
  • 原文地址:https://www.cnblogs.com/moxia1234/p/11397827.html
Copyright © 2011-2022 走看看