标签:ack tween 线程 alt tar [] -- current nod
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();
}
}
标签:ack tween 线程 alt tar [] -- current nod
原文地址:https://www.cnblogs.com/Koma-vv/p/9629527.html