有问题的
package com.bjpowernode.t13;
import java.time.Duration;
import java.time.LocalTime;
public class Processor implements Runnable {
private int num;
/*
下面在方法上加入synchronized關鍵字,會有性能問題
*/
@Override
public synchronized void run() {
LocalTime begin = LocalTime.now();
//------下面的代碼不會出現線程安全問題------
System.out.println("模擬其他非線程安全的操作");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//------上面的代碼不會出現線程安全問題------
for (int i = 0; i < 5; i++) {
num += i;
}
System.out.println(Thread.currentThread().getName() + "------->" + num);
//將num重新設置為0,保證其他線程在運行的時候num是0
num = 0;
//------下面的代碼不會出現線程安全問題------
System.out.println("模擬其他非線程安全的操作");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//------上面的代碼不會出現線程安全問題------
LocalTime end = LocalTime.now();
Duration between = Duration.between(begin, end);
System.out.println(Thread.currentThread().getName() +"運行耗時: " + between.getSeconds() +"秒");
}
}
------------------
package com.bjpowernode.t13;
public class Test {
public static void main(String[] args) {
//只創建一個Processor
Processor p = new Processor();
Thread t1 = new Thread(p,"t1");
Thread t2 = new Thread(p,"t2");
t1.start();
t2.start();
}
}
轉載于:https://www.cnblogs.com/Koma-vv/p/9629527.html
總結
- 上一篇: (转)elasticsearch6.0版
- 下一篇: Vue-admin工作整理(四):路由组