// MyRun实现Runnable接口,然后创建一个实例,将这个实例作为多个Thread的参数构造Thread类,然后启动线程,
//发现这几个线程共享了 MyRun#ato 变量
// 然而上面这个实现接口改成继承Thread,其他都不变,也没啥两样
public class ShareTest {
private static class MyRun implements Runnable {
private volatile AtomicInteger ato = new AtomicInteger(5);
@Override
public void run() {
while (true) {
int tmp = ato.decrementAndGet();
System.out.println(Thread.currentThread() + " : " + tmp);
if (tmp <= 0) {
break;
}
}
}
}
public static void main(String[] args) throws InterruptedException {
MyRun run = new MyRun();
Thread thread1 = new Thread(run, "线程1");
Thread thread2 = new Thread(run, "线程2");
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println("over");
}
}
// 上面除了说明使用Runnable更利于资源共享神马的,其实并没有之外,还有一个比较有意思的,为什么会输出-1?
//如果我这个任务是售票的话,妥妥的就超卖了,这个问题留待后续详解
public class ShareTest {
private static class MyRun extends Thread {
private volatile AtomicInteger ato = new AtomicInteger(5);
@Override
public void run() {
while (true) {
int tmp = ato.decrementAndGet();
System.out.println(Thread.currentThread() + " : " + tmp);
if (tmp <= 0) {
break;
}
}
}
}
public static void main(String[] args) throws InterruptedException {
MyRun run = new MyRun();
Thread thread1 = new Thread(run, "线程1");
Thread thread2 = new Thread(run, "线程2");
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println("over");
}
}