java实现线程安全代码的分享
下文笔者讲述线程安全代码的编写示例,如下所示
方式1:
使用synchronized关键字实现线程安全
方式2:
使用AtomicInteger原子类型变量
例1:
package com.java265.other;
public class XianChengBuAnQuan {
/**
* java265.com 线程不安全的示例
*/
public static int num = 0;
public static void main(String[] args) {
System.out.println("程序开始运行!");
for (int i = 0; i < 5; i++) {
// 开启新线程
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 200; j++) {
synchronized (XianChengBuAnQuan.class) {
num++;
}
}
}
}).start();
}
/* 休眠15秒,保证所有线程执行完成 */
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("num=" + num);
}
}
例2:
package com.java265.other;
import java.util.concurrent.atomic.AtomicInteger;
public class XianChengBuAnQuan {
/**
* java265.com 线程不安全的示例
*/
public static AtomicInteger num = new AtomicInteger(0);
public static void main(String[] args) {
System.out.println("程序开始运行!");
for (int i = 0; i < 5; i++) {
// 开启新线程
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 200; j++) {
num.incrementAndGet();
}
}
}).start();
}
/* 休眠15秒,保证所有线程执行完成 */
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("num=" + num.get());
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


