【7】 常见线程不安全的类与写法

 StringBuilder 不安全

StringBuilder 不安全,但是可以放在方法内局部变量,是堆栈封闭的,

StrinBuffer  安全

synchronized关键字性能损耗,

查看append方法:stringBuffer.append("h");

SimpleDateFormat 不安全,除非定义局部变量堆栈封闭

  public static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
public static void dateCall(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        try {
            simpleDateFormat.parse("20180903");
        } catch (ParseException e) {
            log.info("解析日期异常");
            e.printStackTrace();
        }
    }

joda-time -SimpleDateFormat- 安全的日期包

    <!--安全的日期类-->
<!-- https://mvnrepository.com/artifact/joda-time/joda-time -->
	<dependency>
			<groupId>joda-time</groupId>
			<artifactId>joda-time</artifactId>
			<version>2.9</version>
		</dependency>

实现代码

package com.mmall.concurrency.unsafeClass;

import com.mmall.concurrency.annotations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;


import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

@Slf4j
@NotThreadSafe
public class jodaDateTime {
    public static int clientTotal = 5000;
    public static int threadTotal = 200;
    //  jodaTime
    // public static DateTimeFormatter dateTimeFormatter = new DateTimeFormatter("yyyyMMdd");
    public static DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyyMMdd");

    public static void main(String[] args) throws Exception{
        // 定义线程池和信号量
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i< clientTotal; i++){
            final int count = i;
            executorService.execute( () -> {
                // 线程里执行,加解锁,中间执行
                try {
                    semaphore.acquire();
                    dateCall(count);
                    semaphore.release();
                }catch (Exception e){
                    log.error("信号量捕获异常 ");
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            } );
        } // for
        countDownLatch.await();
        executorService.shutdown();

    }

    private static void dateCall(int j){
        log.info("{},{}",j, DateTime.parse("20190723",dateTimeFormatter));
    }
}
jodaDateTime - 4165,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4054,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4046,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4167,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4050,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4169,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4161,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4170,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4033,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4113,2019-07-23T00:00:00.000+08:00
jodaDateTime - 4138,2019-0

最常用的集合数据结构-- 当然有对应安全的


@Slf4j
@NotThreadSafe
public class HashSetDemo {
    public static int clientTotal = 5000;
    public static int threadTotal = 200;

    public static Set<Integer> set = new HashSet<>();

    public static void main(String[] args) throws Exception{
        // 定义线程池和信号量
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i< clientTotal; i++){
            final int count = i;
            executorService.execute( () -> {
                // 线程里执行,加解锁,中间执行
                try {
                    semaphore.acquire();
                    hash(count);
                    semaphore.release();
                }catch (Exception e){
                    log.error("信号量捕获异常 ");
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            } );
        } // for
        countDownLatch.await();
        executorService.shutdown();
        log.info("set不安全:{}",set.size());
    }

    private static void hash(int j){
        set.add(j);
    }
}

接下来看看那些不安全的写法

两个线程同时判断-同时符合-同时处理-线程安全问题

因为两个操作之间有间隔,不是原子性

结局办法 -- 加个锁-  原子性 -- CAS

总结:

*  这几个写法查资料单独学习

ExecutorService executorService = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(threadTotal);
final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);

*  除了上面提到的几个类,还有很多线程不安全的类

### Java多线程的实现方法 在Java中,多线程的实现主要依赖于`Thread``Runnable`接口。这两种方式都可以用来创建启动线程,但它们各有优缺点。 #### 1. 继承`Thread` 通过继承`Thread`并重写其`run()`方法,可以创建一个新的线程。这种方式简单直观,但由于Java支持多重继承,因此如果一个已经继承了其他,则能使用这种方法来实现线程[^3]。 ```java public class MyThread extends Thread { @Override public void run() { // 线程执行的代码 System.out.println("Hello from thread!"); } public static void main(String[] args) { MyThread myThread = new MyThread(); myThread.start(); // 启动新线程 } } ``` #### 2. 实现`Runnable`接口 另一种常见的方法是实现`Runnable`接口。这种方式允许将任务线程分离,使得代码更加灵活,并且可以在多个线程之间共享同一个`Runnable`实例。这是推荐的做法,因为它避免了多重继承的问题。 ```java public class MyRunnable implements Runnable { @Override public void run() { // 线程执行的代码 System.out.println("Hello from runnable!"); } public static void main(String[] args) { Thread thread = new Thread(new MyRunnable()); thread.start(); // 启动新线程 } } ``` #### 3. 使用`ExecutorService` 对于更复杂的并发需求,Java提供了`ExecutorService`接口,它简化了线程池的管理。通过`Executors`工厂,可以轻松创建固定大小的线程池、缓存线程池或单一线程池等。这有助于提高应用程序的性能资源利用率[^2]。 ```java import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ExecutorExample { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(5); // 创建一个包含5个线程线程池 for (int i = 0; i < 10; i++) { Runnable worker = new WorkerThread('' + i); executor.execute(worker); // 提交任务给线程池 } executor.shutdown(); // 关闭线程池 } } class WorkerThread implements Runnable { private String command; public WorkerThread(String s) { this.command = s; } @Override public void run() { System.out.println(Thread.currentThread().getName() + " Start. Command = " + command); processCommand(); System.out.println(Thread.currentThread().getName() + " End."); } private void processCommand() { try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } } ``` ### 最佳实践 #### 1. 避免死锁 死锁是指两个或更多线程互相等待对方释放资源的情况,导致所有涉及的线程都无法继续执行。为了避免死锁,应确保在获取多个锁时遵循一致的顺序,并尽量减少锁的持有时间[^4]。 #### 2. 正确使用同步机制 为了保证线程安全,需要正确使用同步机制。Java提供了`synchronized`关键字`ReentrantLock`来控制对共享资源的访问。使用这些工具时应注意粒度,以防止必要的性能损失[^4]。 #### 3. 利用线程局部变量(ThreadLocal) 当需要为每个线程提供独立的变量副本时,可以使用`ThreadLocal`。这样可以避免因线程间共享数据而导致的竞争条件问题。 #### 4. 异常处理 在线程中抛出的未捕获异常可能会导致程序崩溃而没有明确的错误信息。因此,在编写多线程程序时,应该为每个线程设置默认的异常处理器,以便能够妥善处理任何未被捕获的异常[^1]。 #### 5. 资源管理关闭 在使用完线程后,特别是使用`ExecutorService`时,应当调用`shutdown()`方法来优雅地关闭线程池,确保所有的任务都已完成并且系统资源得到释放[^2]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值