public class Count { private int num; //public void count() { // for(int i = 1; i <= 100; i ) { // num = i; // } // System.out.println(Thread.currentThread().getName() "-" num); //} public int getNum() { return num; } public void increment(int i) { num = num i; } }
public class ThreadTest { public static void main(String[] args) { Runnable runnable = new Runnable() { Count count = new Count(); @Override public void run() { for (int i = 0; i < 1000; i ) { count.increment(1); } System.out.println(Thread.currentThread().getName() "-" count.getNum()); try { Thread.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } } }; for(int i = 0; i < 10; i ) { Thread thread = new Thread(runnable); thread.start(); } } }
Thread-0-1660 Thread-2-2660 Thread-3-3660 Thread-1-1660 Thread-4-4882 Thread-5-5579 Thread-6-6579 Thread-7-7579 Thread-8-8579 Thread-9-9579
public class Count { public void count() { int number = 0; for(int i = 0; i < 1000; i ) { number = 1; } System.out.println(Thread.currentThread().getName() "-" number); } }
public class ThreadTest { public static void main(String[] args) { Runnable runnable = new Runnable() { Count count = new Count(); @Override public void run() { count.count(); try { Thread.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } } }; for(int i = 0; i < 10; i ) { Thread thread = new Thread(runnable); thread.start(); } } }
Thread-0-1000 Thread-3-1000 Thread-4-1000 Thread-1-1000 Thread-2-1000 Thread-5-1000 Thread-6-1000 Thread-7-1000 Thread-8-1000 Thread-9-1000
public class ThreadTest { public static void main(String[] args) { Runnable runnable = new Runnable() { @Override public void run() { Count count = new Count(); for (int i = 0; i < 1000; i ) { count.increment(1); } System.out.println(Thread.currentThread().getName() "-" count.getNum()); try { Thread.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } } }; for(int i = 0; i < 10; i ) { Thread thread = new Thread(runnable); thread.start(); } } }
Thread-1-1000 Thread-3-1000 Thread-2-1000 Thread-0-1000 Thread-5-1000 Thread-4-1000 Thread-6-1000 Thread-7-1000 Thread-8-1000 Thread-9-1000
END 十期推荐 【241期】面试官:你了解JVM中的ZGC垃圾收集器吗? 【242期】面试官:Spring AOP有哪些通知类型,它们的执行顺序是怎样的? 【243期】面试官:什么是前缀索引、为什么要用前缀使用、用在什么场景下? 【244期】万字 图解 Redis,面试不用愁了! 【245期】面试官:MySQL发生死锁有哪些原因,怎么避免? 【246期】面试官:说说你对 RabbitMQ 的理解以及使用它的场景 【247期】记一次Java面试中遇到的三个问题及感悟! 【248期】面试官:你能说几个Java8中Stream对列表去重的方法吗? 【249期】关于Java中的异常,面试可以问的都在这里了! 【250期】关于Mybatis知识点,面试可以问的都在这里了! ? ~