[英]Parallel programming with threads on specific static method in java
I have this code: 我有以下代码:
public final class AClass{
static Long x=0;
public static Long aMethod(args...){
//commands
x = aMethod(args...);
x += aMethod(args...);
//commands
}
}
I want to execute the two lines of code(the two calls of aMethod
) parallel with threads. 我想执行与线程并行的两行代码( aMethod
的两次调用)。
This is a relatively simple problem and the following code should solve your predicament 这是一个相对简单的问题,以下代码可以解决您的难题
Thread thread1 = new Thread() {
public void run() {
x = aMethod(args...);
}
};
Thread thread2 = new Thread() {
public void run() {
x += aMethod(args...);
}
};
thread1.start();
thread2.start();
Then you join the result with: 然后,您将结果与:
thread1.join();
thread2.join();
These 2 lines of code will throw an InterruptedException and will need to be handled with a try/catch 这两行代码将引发InterruptedException,并且需要使用try / catch进行处理
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.