package com.mhm.test;
public class Test7 extends Thread {
public static int n = 0;
public void run() {
int m = n;
yield();
m++;
n = m;
}
public static void main(String[] args) throws Exception {
Test7 myThread = new Test7();
Thread threads[] = new Thread[100];
for (int i = 0; i < threads.length; i++)
threads[i] = new Thread(myThread);
for (int i = 0; i < threads.length; i++)
threads[i].start();
for (int i = 0; i < threads.length; i++)
threads[i].join();
System.out.println("n = " + Test7.n);
}
}
当这段代码执行完后,结果可能不是100,因为出现了脏数据
解决办法是在run() 前加synchronized
转载于http://java.chinaitlab.com/line/779590.html
在23种设计模式中的单件(Singleton)模式如果按传统的方法设计,也是线程不安全的,下面的代码是一个线程不安全的单件模式。
class Singleton
{
private static Singleton sample;
private Singleton()
{
}
public static Singleton getInstance()
{
if (sample == null)
{
Thread.yield(); // 为了放大Singleton模式的线程不安全性
sample = new Singleton();
}
return sample;
}
}
public class MyThread extends Thread
{
public void run()
{
Singleton singleton = Singleton.getInstance();
System.out.println(singleton.hashCode());
}
public static void main(String[] args)
{
Thread threads[] = new Thread[5];
for (int i = 0; i < threads.length; i++)
threads[i] = new MyThread();
for (int i = 0; i < threads.length; i++)
threads[i].start();
}
}
要想使上面的单例模式线程安全,只要在静态方法getInstance()前加上
synchronized就可以了