public class UnsafeSequence { private static int count = 0; public static void main(String[] args) { List
list =
new ArrayList
();
for (
int i =
0; i <
10000; i++) { Thread t =
new Thread(
new Runnable() { @Override
public
void
run() { countSequence(); } }); t.start(); list.add(t); }
try {
for (Thread t : list) { t.
join(); } }
catch (InterruptedException e) { e.printStackTrace(); } System.
out.println(count); }
public
static
int
countSequence() {
try {
// 模拟程序耗时
long l =
new Random().nextInt(
9) *
10; Thread.sleep(l); }
catch (InterruptedException e) { e.printStackTrace(); }
return count++; } }
怎么解决它?有很多方式,最简单直接的方法就是用synchronized关键字,代码修改如下:
public class UnsafeSequence { private static int count = 0; public static void main(String[] args) { List
list =
new ArrayList
();
for (
int i =
0; i <
10000; i++) { Thread t =
new Thread(
new Runnable() { @Override
public
void
run() { countSequence(); } }); t.start(); list.add(t); }
try {
for (Thread t : list) { t.
join(); } }
catch (InterruptedException e) { e.printStackTrace(); } System.
out.println(count); }
public
static
int
countSequence() {
try {
// 模拟程序耗时
long l =
new Random().nextInt(
9) *
10; Thread.sleep(l); }
catch (InterruptedException e) { e.printStackTrace(); }
/////////这里用了synchronized 关键字,就是这么简单,既保证了可见性又保证了原子性。 synchronized (UnsafeSequence.class) {
return count++; } } }
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/217092.html原文链接:https://javaforall.net
