解决方案 »

  1.   

    Integer是final的,++操作会重新生成一个对象或数值。
    n = n+1;这样试试呢?
      

  2.   

    好吧,我说错了。。n++和n=n+1一样的效果。。
      

  3.   


    就是在测试多线程的锁, synchronized (n) {……}开始用  public static Integer n = new Integer(0);这个对象当锁,发现不起作用,然后换成   public static byte[] lock=new byte[0];对象,就好了,不知道是不是 在线程里面被操作的对象n,不能用作锁对象?
      

  4.   


    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.atomic.AtomicInteger;public class Test01 implements Runnable {
    private String name;
    private TestThread t;
    private AtomicInteger count = new AtomicInteger(); public Test01(String name, TestThread t) {
    super();
    this.name = name;
    this.t = t;
    } @Override
    public void run() {
    Thread.currentThread().setName(name);
    while (true) {
    t.showCount();
    if (10 > count.getAndIncrement()) {
    break;
    }
    }
    } /**
     * @param args
     */
    public static void main(String[] args) {
    ExecutorService exec = Executors.newCachedThreadPool();
    TestThread t = new TestThread();
    for (int i = 0; i < Runtime.getRuntime().availableProcessors() * 4; i++) {
    exec.execute(new Test01("thread-" + i, t));
    }
    exec.shutdown(); }
    }class TestThread {
    private Object obj = new Object();
    private int count; public void showCount() {
    synchronized (obj) {
    //synchronized (this) {//这里可以用obj,可以用this
    try {
    System.out.println(Thread.currentThread().getName()
    + " before --> " + count);
    synchronized (obj) {
    count++;
    }
    System.out.println(Thread.currentThread().getName()
    + " after --> " + count);
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }
    }
    看看这段代码。
    我这里使用了对象的内部锁,保证线程的安全性。可以用我上面的private Object obj = new Object();
    synchronized (obj)也可以使用synchronized (this)两者的效果是一样的。当然你也可以使用显示的
    private Lock lock = new ReentrantLock();
    进行加锁,解锁。
    你用public static Integer n = new Integer(0);的时候,在后面执行了 n++; 操作。你要明白,n++ 这个操作,其实是生产了新的n,然后给n进行赋值。你的锁的“不变性”早就不复存在了。你最好打印出来的n,早就不是最开始的n了。去看看《Java并发编程实战》吧。
      

  5.   

    你说使用 public static byte[] lock=new byte[0] 就好了?为什么?因为你在代码中,没有对这个变量进行修改,public static byte[] lock=new byte[0] 和我上面写的
    private Object obj = new Object();
    synchronized (obj)

    synchronized (this)
    没有任何的区别,都是对象的内置锁。同步它,都是线程安全的。你的
    public static Integer n = new Integer(0);
    被你进行 n++; 操作修改了。