当前位置: 代码迷 >> J2SE >> 线程同步,该怎么解决
  详细解决方案

线程同步,该怎么解决

热度:85   发布时间:2016-04-23 20:35:20.0
线程同步
//这里的线程同步了
class TestSum {
int sum;

synchronized int ArraySum(int[] nums) {
sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
try {
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
System.out.println(sum);
}
System.out.println("Thread ending.\n");
return sum;
}
}

class MyThread1 implements Runnable {
int[] nums;
Thread thrd;
static TestSum objSum = new TestSum();

public MyThread1(int[] nums) {
this.nums = nums;

}
public MyThread1( MyThread1 mt) {
thrd = new Thread(mt);

thrd.start();
}

public void run() {
objSum.ArraySum(nums);
}
}

public class Demo1 {

public static void main(String[] args) {
int[] nums = { 1, 2, 3 };
MyThread1 ob3 = new MyThread1(nums);
MyThread1 ob4 = new MyThread1(nums);
MyThread1 ob1 = new MyThread1(ob3);
MyThread1 ob2 = new MyThread1(ob4);
}

}

//这里的线程却没有同步:
class MyThread5 implements Runnable {
int[] nums = new int[5];
int sum;

public MyThread5(int[] nums) {
this.nums = nums;
}

 synchronized int arrySum() {
sum = 0;
for (int i = 0; i < nums.length; i++) {
try {
Thread.sleep(2000);
} catch (Exception e) {

}
sum += nums[i];
System.out.println(sum);
}
System.out.println("Thread ending.\n");
return sum;
}

public void run() {
arrySum();
}
}

public class Demo5 {

public static void main(String[] args) throws InterruptedException {
int[] nums = { 1, 2, 3, 4, 5 };
MyThread5 mt1 = new MyThread5(nums);
MyThread5 mt2 = new MyThread5(nums);
Thread thd1 = new Thread(mt1);
Thread thd2 = new Thread(mt2);
thd1.start();
thd2.start();
}

}
看了很久也没有想清楚,为什么第一段代码同步了,而第二段却没有同步。
------解决方案--------------------
线程同步不同步要看你synchronized锁的是不是同一个锁 锁定同一个锁的两个线程才会同步

你的第一段代码 synchronized锁的是TestSum的当前对象 也就是this 这个this代表了一个TestSum的当前对象 也就是你写的那句static TestSum objSum = new TestSum()中的objSum 因为你加了static 所以mt1和mt2中的objSum是同一个对象 线程thd1和thd2锁的是一个锁 所以就同步了

你的第二段synchronized锁的是MyThread5的当前对象 也就是你写的MyThread5 mt1 = new MyThread5(nums)和MyThread5 mt2 = new MyThread5(nums); 注意因为你没加static 所以mt1和mt2不是同一个对象 线程锁的不是同一个锁  所以不同步

你可加把第一段中的static去了 第一段就不同步了 
还可以把第二段中的Thread thd2 = new Thread(mt2);中的mt2换成mt1 第二段就同步了
  相关解决方案