为什么要在多线程中进行数据同步

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就可以了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值