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的线程不能共享资源。这个例子是说明这个问题吗?