1. // MyRun实现Runnable接口,然后创建一个实例,将这个实例作为多个Thread的参数构造Thread类,然后启动线程,
    2. //发现这几个线程共享了 MyRun#ato 变量
    3. // 然而上面这个实现接口改成继承Thread,其他都不变,也没啥两样
    4. public class ShareTest {
    5. private static class MyRun implements Runnable {
    6. private volatile AtomicInteger ato = new AtomicInteger(5);
    7. @Override
    8. public void run() {
    9. while (true) {
    10. int tmp = ato.decrementAndGet();
    11. System.out.println(Thread.currentThread() + " : " + tmp);
    12. if (tmp <= 0) {
    13. break;
    14. }
    15. }
    16. }
    17. }
    18. public static void main(String[] args) throws InterruptedException {
    19. MyRun run = new MyRun();
    20. Thread thread1 = new Thread(run, "线程1");
    21. Thread thread2 = new Thread(run, "线程2");
    22. thread1.start();
    23. thread2.start();
    24. thread1.join();
    25. thread2.join();
    26. System.out.println("over");
    27. }
    28. }
    29. // 上面除了说明使用Runnable更利于资源共享神马的,其实并没有之外,还有一个比较有意思的,为什么会输出-1?
    30. //如果我这个任务是售票的话,妥妥的就超卖了,这个问题留待后续详解
    31. public class ShareTest {
    32. private static class MyRun extends Thread {
    33. private volatile AtomicInteger ato = new AtomicInteger(5);
    34. @Override
    35. public void run() {
    36. while (true) {
    37. int tmp = ato.decrementAndGet();
    38. System.out.println(Thread.currentThread() + " : " + tmp);
    39. if (tmp <= 0) {
    40. break;
    41. }
    42. }
    43. }
    44. }
    45. public static void main(String[] args) throws InterruptedException {
    46. MyRun run = new MyRun();
    47. Thread thread1 = new Thread(run, "线程1");
    48. Thread thread2 = new Thread(run, "线程2");
    49. thread1.start();
    50. thread2.start();
    51. thread1.join();
    52. thread2.join();
    53. System.out.println("over");
    54. }
    55. }