互联网架构学习-第一章 并发编程基础(二)

1 第一章 并发编程基础

1.2 线程安全核心概念

线程安全概念:当多个线程访问某一个类(对象或方法)时,这个类始终都能表现出正确的行为,那么这个类(对象或方法)就是线程安全的。
synchronized:可以在任意对象及方法上加锁,而加锁的这段代码称为“互斥区”或“临界区”。
当多个线程访问Thread的run方法时,以排队的方式进行处理(这里排对是按照CPU分配的先后顺序而定的),一个线程想要执行synchronized修饰的方法里的代码,首先是尝试获得锁,如果拿到锁,执行synchronized代码体内容;拿不到锁,这个线程就会不断的尝试获得这把锁,直到拿到为止,而且是多个线程同时去竞争这把锁。(也就是会有锁竞争的问题)。

public class MyThread extends Thread {
	
	private int count = 5;
	
	public void run() {
		count--;
		System.out.println(this.currentThread().getName() + " count=" + count);
	}
	
	public static void main(String[] args) {
		MyThread myTd = new  MyThread();
		
		Thread t1 = new Thread(myTd, "t1");
		Thread t2 = new Thread(myTd, "t2");
		Thread t3 = new Thread(myTd, "t3");
		Thread t4 = new Thread(myTd, "t4");
		Thread t5 = new Thread(myTd, "t5");
		
		t1.start();
		t2.start();
		t3.start(); 
		t4.start();
		t5.start();
	}
}

上面代码的执行结果如下图所示,可以看到,count的结果并不是预期的结果。可以清楚知道这种写法不是线程安全的。
在这里插入图片描述

要变得线程安全,有个很简单的办法,就是在run方法增加一个修饰关键字synchronized 。

	public synchronized void run() {
		count--;
		System.out.println(this.currentThread().getName() + " count=" + count);
	}

一个线程想要执行synchronized修饰的方法里的代码,首先是尝试获得锁,如果拿到锁,执行synchronized代码体内容;拿不到锁,这个线程就会不断的尝试获得这把锁,直到拿到为止。新的执行结果如下,符合我们的预期。
在这里插入图片描述

线程之间通信

使用wait / notify 方法实现线程间的通信
注意这两个方法都是object的类的方法,换句话说java为所有的对象都提供了这两个方法

  • wait 和 notify 必须配合 synchronized 关键字使用
  • wait方法释放锁,notify方法不释放锁
ThreadLocal

线程局部变量,是一种多线程间并发访问变量的解决方案。与其synchronized等加锁的方式不同,ThreadLocal完全不提供锁,而使用以空间换时间的手段,为每个线程提供变量的独立副本,以保障线程安全。
从下面代码运行的结果可以看出来,同一个变量,线程之间互不影响。

public class UseThreadLocal {

	public static ThreadLocal<String> threadLocal = new ThreadLocal<>();
		
	public void setThreadLocal(String value) {
		threadLocal.set(value);
	}
	
	public String getThreadLocal() {
		return threadLocal.get();
	}
	
	public static void main(String[] args) throws InterruptedException {
		UseThreadLocal utlLocal = new UseThreadLocal();
		Thread t1 = new Thread(new Runnable() {
			
			@Override
			public void run() {
				utlLocal.setThreadLocal("张三");
				System.err.println("子线程t1:" + utlLocal.getThreadLocal());
			}
		}, "t1"); 

		Thread t2 = new Thread(new Runnable() {
			
			@Override
			public void run() {
			
				utlLocal.setThreadLocal("李四");
				System.err.println("子线程t2:" + utlLocal.getThreadLocal());
			}
		}, "t2");
		
		Thread.sleep(1000);
		t1.start();
		t2.start();
		System.err.println("主线程:" + utlLocal.getThreadLocal());

	}
}

下面是运行结果:
在这里插入图片描述

线程间即时通讯例子
先看下面的例子

import java.util.ArrayList;
import java.util.List;

public class ListAdd1 {

	// 1 定义的承装字符串的容器
	private static List list = new ArrayList<String>();	
	
	// 2 追加方法
	public void add(String valString){
		list.add(valString);
	}
	public int size(){
		return list.size();
	}
	
	public static void main(String[] args) throws InterruptedException {
		
		final ListAdd1 list1 = new ListAdd1();
		
		final Object lock = new Object();
		
		// 线程A
		Thread A = new Thread(new Runnable() {
			@Override
			public void run() {
				synchronized (lock) {
					for(int i = 0; i <6; i++){
						list1.add("内容");
						System.out.println("当前线程:" + Thread.currentThread().getName() + ", 添加了一个元素..");
						try {
							Thread.sleep(500);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
						if(list.size() == 3) {
							System.err.println("已经发出了唤醒通知!");
							lock.notify();
						}
					}						
				}
			}
		}, "A");
		
		// 线程B
		Thread B = new Thread(new Runnable() {
			@Override
			public void run() {
				boolean running = true; 
				while(running){
					synchronized (lock) {
						if(list1.size() != 3) {
							try {
								lock.wait();
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}
					System.err.println("当前线程收到通知:" + Thread.currentThread().getName() + " list size = 5 线程停止..");
					running = false;
				}
			}
		}, "B");	
		
		B.start();
		Thread.sleep(100);
		A.start();
	}
}

运行结果如下:
在这里插入图片描述
可以看到,虽然线程A早早发出了唤醒通知,但线程B最后才执行。因为 notify不释放锁,要等到线程执行完。wait则可以立即释放锁。
解决办法1. 放弃锁,使用CountDownLatch。

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

public class ListAdd2 {

	// 1 定义的承装字符串的容器
	private static List list = new ArrayList();

	// 2 追加方法
	public void add(String valString) {
		list.add(valString);
	}

	public int size() {
		return list.size();
	}

	public static void main(String[] args) throws InterruptedException {

		final ListAdd2 list1 = new ListAdd2();

		final CountDownLatch latch = new CountDownLatch(1);

		// 线程A
		Thread A = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					for (int i = 0; i < 6; i++) {
						list1.add("内容");
						System.out.println("当前线程:" + Thread.currentThread().getName() + ", 添加了一个元素..");
						Thread.sleep(500);
						if (list.size() == 3) {
							System.err.println("已经发出了唤醒通知!");
							latch.countDown();
						}
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}, "A");

		// 线程B
		Thread B = new Thread(new Runnable() {
			@Override
			public void run() {
				boolean tContinue = true;
				while (tContinue) {
					if (list1.size() != 3) {
						try {
							latch.await();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					System.err.println("当前线程收到通知:" + Thread.currentThread().getName() + " list size = 3 线程停止..");
					tContinue = false;
				}
			}
		}, "B");

		B.start();
		Thread.sleep(100);
		A.start();
	}
}

下面是执行结果。可以看出,线程B能够及时感知到size变化。
在这里插入图片描述

还有一种更加方便的办法,就是使用volatile关键字。

import java.util.ArrayList;
import java.util.List;

public class ListAdd3 {

	// 1 定义的承装字符串的容器
	private volatile static List list = new ArrayList();

	// 2 追加方法
	public void add(String valString) {
		list.add(valString);
	}

	public int size() {
		return list.size();
	}

	public static void main(String[] args) throws InterruptedException {

		final ListAdd3 list1 = new ListAdd3();

		// 线程A
		Thread A = new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					for (int i = 0; i < 6; i++) {
						list1.add("内容");
						System.out.println("当前线程:" + Thread.currentThread().getName() + ", 添加了一个元素..");
						Thread.sleep(500);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}, "A");

		// 线程B
		Thread B = new Thread(new Runnable() {
			@Override
			public void run() {
				boolean tContinue = true;
				while (tContinue) {
					if (list1.size() == 3) {
						System.err.println("B线程收到通知:" + " list size = 3 线程停止...");
						tContinue = false;
					}
				}
			}
		}, "B");

		B.start();
		Thread.sleep(100);
		A.start();
	}
}


这里是运行结果。
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值