一个程序,多个线程同时操作一个变量,给这个变量+1()。功能很简单,可是怎么样去实现呢?这其中涉及到了哪些问题?
最基础想法
见代码:
1 public class Test extends Thread { 2 public static int amount = 0; 3 4 public void run() { 5 amount++; 6 } 7 8 public static void main(String[] args) { 9 int num_thread = 100; 10 for (int i = 0; i < num_thread; i++) { 11 new Test().start(); 12 } 13 try { 14 Thread.sleep(3 * 1000); 15 } catch (InterruptedException e) { 16 e.printStackTrace(); 17 } 18 System.out.println(amount); 19 } 20 }