JaveEE-线程安全问题(基础篇)

多线程

1.多线程的实现方法

多线程的实现要依靠Thead类,实现一个线程用到了lamba表达式的应用,具体实现可以参考以下代码

Thead t1=new Thead(()->{

//代码块



});//实现t1线程


Thead t2=new Thead(()->{


//代码块
}); //实现t2线程


t1.start();
t2.start();
//开始运行t1,t2线程;
t1.join();
t2.join();

//等待t1,t2线程结束。

实现多线程时要抛出InterruptException ,不然会提示异常。

2.线程安全

在这儿先讲一下比较简单实现线程安全的方式,当两个线程读取的内存的数据有重叠时,我们避免在某个线程中已经修改了数据后,防止其他线程使用时读取错误导致运行结果错误,我们可以利用加锁:关键字为

synchronized,sycchronized()需要传参,但需要我们注意的是传参的时候,参数必须是以下几种类型

1.一个类

2.一个方法

3.一个静态方法

4.一段代码块

以下为传一个类对象的用法

import java.util.concurrent.atomic.AtomicInteger;

public class Demo11 {
    public static void main(String[] args) throws InterruptedException {
Counter counter=new Counter();

     Thread thread1=new Thread(()->{
         synchronized (counter){
             for (int i = 0; i <10000 ; i++) {
             counter.increase();;

             }
         }
     });
     Thread thread2=new Thread(()->{
        synchronized (counter){
            for (int i = 0; i <10000 ; i++) {
                counter.increase();
            }
        }
     });//锁同一个对象使线程安全
     thread1.start();;
     thread2.start();;
     //开始运行两个线程
     thread1.join();
     thread2.join();
     //等待线程运行结束
        System.out.println("count累加后的结果为"+counter.count);
    }
}
class  Counter{
    int count=0;
    public void increase(){
        count++;
    }
}

当我们不用synchronized时这两个线程会一起执行,因为修改的是同一个对象,所以当运行时结果就会出错,因为同时读取内存相同的数据就会导致线程不安全,当加上synchronized时,结果就是20000也是正确的运算结果。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大鹏在路上_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值