同时使用两个线程访问两个同步块

问题描述:

任何人都可以告诉我如何使用2个线程同时访问一个方法,该方法有2个参数和2个同步块。我想要的是,一个线程执行第一个同步块,另一个线程执行第二个同步块。同时使用两个线程访问两个同步块

public class myThread{ 

public static class TwoSums implements Runnable{ 
    private int sum1 = 0; 
    private int sum2 = 0; 

    public void add(int a, int b){ 
     synchronized(this){ 
      sum1 += a; 
      String name = Thread.currentThread().getName(); 
      System.out.println("Thread name that was accessing this code 1 : "+name); 
     } 

     synchronized(this){ 
      sum2 += b; 
      String name = Thread.currentThread().getName(); 
      System.out.println("Thread name that was accessing this code 2 : "+name); 
     } 
    } 

    @Override 
    public void run() { 
     add(10,20); 
    } 
} 

public static void main(String[] args) { 
    TwoSums task = new TwoSums(); 

    Thread t1 = new Thread(task, "Thread 1"); 
    Thread t2 = new Thread(task, "Thread 2"); 

    t1.start(); 
    t2.start(); 
} 

}

此代码含有一些代码:由任何线程和同步块不作任何异常http://tutorials.jenkov.com/java-concurrency/race-conditions-and-critical-sections.html

+1

第二个线程不能得到第二synchronized块不先执行第一个... – immibis

+2

把你的方法到2点不同的方法。 –

+0

所以这意味着我不能在一种方法中访问2线程的同步块? – Okem

所述指令被处理顺序。下面的代码做你问什么,但看起来只是作为一个练习,没有任何真正有意义的应用

public static class TwoSums implements Runnable { 
    private int sum1 = 0; 
    private int sum2 = 0; 

    public void add(int a, int b) { 
     if ("Thread 1".equals(Thread.currentThread().getName())) { 
      synchronized (this) { 
       sum1 += a; 
       String name = Thread.currentThread().getName(); 
       System.out.println("Thread name that was accessing this code 1 : " + name); 
      } 
     } 
     if ("Thread 2".equals(Thread.currentThread().getName())) { 
      synchronized (this) { 
       sum2 += b; 
       String name = Thread.currentThread().getName(); 
       System.out.println("Thread name that was accessing this code 2 : " + name); 
      } 
     } 
    } 

    @Override 
    public void run() { 
     add(10, 20); 
    } 
} 

为了实现这一目标(我不打算讨论,如果你正在做的是对还是错了,因为我想,你只是在学习如何工作),你需要使用ReentranLock接口及其实现锁类:

Lock lock = new ReentrantLock(); 

你应该在你TwoSum类中声明该对象,并使用内部的锁定对象你的添加方法。 ReentrantLock接口有一个名为tryLock的方法,它将尝试获取被调用对象的锁定,如果成功或否则返回布尔值true。所以对于第一个线程它将返回true,但对于第二个线程它将返回false。因此,所有你需要把一个验证

if(lock.tryLock()) //Execute block code 1 
else // Execute block code 2