【发布时间】:2021-01-06 09:15:27
【问题描述】:
我正在尝试学习 Java 中的多线程和并行执行。我写了这样的示例代码:
public class MemoryManagement1 {
public static int counter1 = 0;
public static int counter2 = 0;
public static final Object lock1= new Object();
public static final Object lock2= new Object();
public static void increment1() {
synchronized(lock1) {
counter1 ++;
}
}
public static void increment2() {
synchronized(lock2) {
counter2 ++;
}
}
public static void processes() {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 4; i++) {
increment1();
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 4; i++) {
increment2();
}
}
});
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Counter value is :" + counter1);
System.out.println("Counter value is :" + counter2);
}
public static void main(String[] args) {
processes();
}
}
代码运行正常,但我怎么知道代码是按照时间片运行还是并行执行。我有一个 4 核的 CPU。据我了解,程序应该并行执行,但我不确定。
【问题讨论】:
-
别忘了“Thread.currentThread().interrupt();”在“InteruptedException”块中。
标签: java multithreading performance parallel-processing