任何人都可以告訴我如何使用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
第二個線程不能得到第二synchronized塊不先執行第一個... – immibis
把你的方法到2點不同的方法。 –
所以這意味着我不能在一種方法中訪問2線程的同步塊? – Okem