java吧 关注:1,243,843贴子:12,717,269
  • 8回复贴,共1

求老鸟,多线程新手问题

只看楼主收藏回复

大神们,为什么这个同步锁没用呢,for循环里越耗时,c和a的值越小,根本有没锁住
public class TestCallable {
public static int a = 0;
public static AtomicInteger c = new AtomicInteger(0);
public static void main(String[] args) {
iThread t1 = new iThread();
iThread t2 = new iThread();
t1.start();
t2.start();
try
{
System.out.println("atomic c: "+c);
System.out.println("int a : "+a);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
class iThread extends Thread{
@Override
public void run() {
synchronized(this)
{
for(int i =0; i<1000; i++){
TestCallable.a++;
TestCallable.c.incrementAndGet();
}
}
}
}


IP属地:广东1楼2017-05-13 22:32回复
    你要锁什么?thread里面的同步关键字锁的是线程本身,当然没用


    2楼2017-05-13 22:47
    收起回复
      另外你start之后立即打印能有什么效果。。


      3楼2017-05-13 22:49
      回复
        public class TestCallable {
        public static int a = 0;
        public static AtomicInteger c = new AtomicInteger(0);
        public static void main(String[] args) throws InterruptedException {
        iThread t1 = new iThread();
        iThread t2 = new iThread();
        t1.start();
        t2.start();
        Thread.sleep(2000);
        try {
        System.out.println("atomic c: " + c);
        System.out.println("int a : " + a);
        } catch (Exception e) {
        e.printStackTrace();
        }
        }
        }
        class iThread extends Thread {
        private static final Object LOCK = new Object();
        @Override
        public void run() {
        for (int i = 0; i < 1000; i++) {
        synchronized (LOCK) {
        TestCallable.a++;
        }
        TestCallable.c.incrementAndGet();
        }
        }
        }


        5楼2017-05-13 22:56
        收起回复