62,626
社区成员
发帖
与我相关
我的任务
分享
public class ThreadLockTest2 implements Runnable{
private static Integer count = 0;
@Override
public void run() {
synchronized(count){
for(int i = 0 ; i < 5 ; i ++){
System.out.println(Thread.currentThread().getName()+"> "+count++);
}
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new ThreadLockTest2(),"th1");
Thread t2 = new Thread(new ThreadLockTest2(),"th2");
t1.start();
t2.start();
}
}
th1> 0
th2> 1
th2> 2
th2> 3
th2> 4
th2> 5
th1> 5
th1> 6
th1> 7
th1> 8
Integer i=0;
Integer i2 = i;
System.out.println(i==i2);//true
Integer i3=i++;
System.out.println(i==i2);//false
System.out.println(i==i3);//false
System.out.println(i2==i3);//true
public class ThreadLockTest2 implements Runnable{
private static Integer count = 0;
@Override
public void run() {
synchronized(this){
for(int i = 0 ; i < 5 ; i ++){
System.out.println(Thread.currentThread().getName()+"> "+count++);
}
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new ThreadLockTest2(),"th1");
Thread t2 = new Thread(new ThreadLockTest2(),"th2");
t1.start();
t2.start();
}
}
public static void main(String[] args) {
Integer i=0;
Integer i2 = i;
Integer i3=i++;
System.out.println(i==i2);//false
System.out.println(i==i3);//false
System.out.println(i2==i3);//true
}
++ 运算符会将count 对象重新赋值. 执行++ 后的count 对象和之前会不一样.
synchronized(count) 这里两个线程锁的不是同一对象,才出现楼主的现象.
synchronized 你用 不可变对象.(ThreadLockTest2.class) 比较好
public class ThreadLockTest2 implements Runnable{
private static Integer count = 0;
private static Object lockObject = new Object();
public void run() {
synchronized(lockObject){
for(int i = 0 ; i < 5 ; i ++){
System.out.println(Thread.currentThread().getName()+"> "+ count++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new ThreadLockTest2(),"th1");
Thread t2 = new Thread(new ThreadLockTest2(),"th2");
t1.start();
t2.start();
}
}