多线程
【程序】是指令和数据的有序集合,是静态的。
【进程process】是指执行程序的一次过程,是动态的。进程是系统资源分配的单位。一个进程至少有一个线程。
【线程thread】线程是CPU调度和执行的单位。
实际的单核和多核,虚拟的多线程和实际的多线程。
【注意】
- 线程就是独立的执行路径;
- 在程序运行时,即使没有自己创建线程,后台也会有多个线程,如主线程,gc线程;
- main()称之为主线程,为系统的入口,用于执行整个程序;
- 在一个进程中,如果开辟了多个线程,线程的运行由调度器安排调度,调度器是与操作系统紧密相关的,先后顺序是不能人为干预的
- 对同一份资源操作时,会存在资源抢夺问题,需加入并发控制;
- 线程会带来额外的开销,如cpu调度时间,并发控制开销;
- 每个线程在自己的工作内存交互,内存控制不当会造成数据不一致
创建线程的三个方法
-
继承Thread类
-
实现Runnable接口
-
实现Callable接口
方法一:继承Thread类
//创建线程方式一:继承Thread类,重写run()方法,调用start开启线程
//总结:线程开启不一定立即执行,由CPU调度执行
public class TestThread1 extends Thread{
public void run(){
//run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("我在看代码---"+i);
}
}
public static void main(String[] args) {
//main方法,主线程
//创建一个线程对象
TestThread1 testThread1 = new TestThread1();
//调用start()方法,开启线程
testThread1.start();
for (int i = 0; i < 20; i++) {
System.out.println("我在学习多线程---"+i);
}
}
}
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
//练习thread,实现多线程同步下载图片
public class TestThread2 extends Thread{
private String url;//网络图片地址
private String name;//保存的文件名
public TestThread2 (String url,String name){
this.url = url;
this.name = name;
}
//下载图片线程的执行体
@Override
public void run() {
webDownloader webDownloader = new webDownloader();
webDownloader.downloader(url,name);
System.out.println("下载了文件,名为: "+ name);
}
public static void main(String[] args) {
TestThread2 t1 = new TestThread2("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2F9dae719a44088488ef29c515e9d9ae15f9e8a0ae816b-s3HN30_fw658&refer=http%3A%2F%2Fhbimg.b0.upaiyun.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1628560496&t=3aff566aeabec5a008fc9f3cb98ff452","1.jpg");
TestThread2 t2 = new TestThread2("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2F9dae719a44088488ef29c515e9d9ae15f9e8a0ae816b-s3HN30_fw658&refer=http%3A%2F%2Fhbimg.b0.upaiyun.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1628560496&t=3aff566aeabec5a008fc9f3cb98ff452","2.jpg");
TestThread2 t3= new TestThread2("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2F9dae719a44088488ef29c515e9d9ae15f9e8a0ae816b-s3HN30_fw658&refer=http%3A%2F%2Fhbimg.b0.upaiyun.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1628560496&t=3aff566aeabec5a008fc9f3cb98ff452","3.jpg");
/**
* 我们认为下载顺序会是t1 t2 t3
* 实际上是同时进行,哪个进行的快,哪个先下载完
*/
t1.start();
t2.start();
t3.start();
}
}
//下载器
class webDownloader{
//下载方法
public void downloader(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常,downloader方法出现问题");
}
}
}
方法二:实现Runnable接口
/**
* 创建线程方式二:
* 实现Runnable接口,重写run()方法
* 把Runnable接口的实现类放入新创建的线程中
* 调用start()方法
*/
public class TestThread3 implements Runnable{
public void run(){
//run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("我在看代码---"+i);
}
}
public static void main(String[] args) {
//创建Runnable接口实现类的对象
TestThread3 t = new TestThread3();
//创建线程对象,通过线程对象来开启线程,代理;调用start()方法,开启线程
// Thread thread = new Thread(t);
// thread.start();
new Thread(t).start();
for (int i = 0; i < 20; i++) {
System.out.println("我在学习多线程---"+i);
}
}
}
/**
* 多个线程操作同一个对象
* 现实中的例子【买火车票】
*
* 总结:多个线程操作同一个资源的情况下,程序不安全,数据紊乱(并发)
*/
public class TestThread4 implements Runnable{
//票数
private int ticketNums = 10;
@Override
public void run() {
while(true){
if (ticketNums <= 0) {
break;
}
//模拟延时
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"--->拿到了第"+ticketNums--+"张票");
}
}
public static void main(String[] args) {
TestThread4 t4 = new TestThread4();
new Thread(t4,"小明").start();
new Thread(t4,"老师").start();
new Thread(t4,"黄牛").start();
}
}
龟兔赛跑
/**
* 模拟龟兔赛跑
*/
public class Race implements Runnable{
//胜利者
private static String winner;
@Override
public void run() {
for (int i = 0; i <= 101; i++) {
//模拟兔子休息
if (Thread.currentThread().getName().equals("兔子") || i%10 == 0){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//判断比赛是否结束
boolean flag = gameOver(i);
if (flag){
break;
}
System.out.println(Thread.currentThread().getName()+"--->跑了"+i+"步");
}
}
//判断是否完成
private boolean gameOver(int steps){
//判断是否有胜利者
if (winner != null){//已经存在胜利者了
return true;
}{
if (steps == 101){
winner = Thread.currentThread().getName();
System.out.println("The winner is "+winner);
return true;
}
}
return false;
}
public static void main(String[] args) {
Race race = new Race();
new Thread(race,"乌龟").start();
new Thread(race,"兔子").start();
}
}
方法三:实现Callable接口
【步骤】
- 实现Callable接口,需要返回值类型
- 重写call方法,需要抛出异常
- 创建目标对象
- 创建执行服务:ExecutorService ser = Executors.newFixedThreadPool(1);
- 提交执行:Future result1 = ser.submit(t1);
- 获取结果:boolean r1 = result1.get()
- 关闭服务:ser.shutdownNow();
/**
* 创建线程方式三:实现Callable接口
* 总结:
* 1、可定义返回值
* 2、抛出异常
*/
public class TestCallable implements Callable<Boolean> {
private String url;//网络图片地址
private String name;//保存的文件名
public TestCallable (String url,String name){
this.url = url;
this.name = name;
}
//下载图片线程的执行体
@Override
public Boolean call() {
webDownloader webDownloader = new webDownloader();
webDownloader.downloader(url,name);
System.out.println("下载了文件,名为: "+ name);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
TestCallable t1 = new TestCallable("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2F9dae719a44088488ef29c515e9d9ae15f9e8a0ae816b-s3HN30_fw658&refer=http%3A%2F%2Fhbimg.b0.upaiyun.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1628560496&t=3aff566aeabec5a008fc9f3cb98ff452","1.jpg");
TestCallable t2 = new TestCallable("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2F9dae719a44088488ef29c515e9d9ae15f9e8a0ae816b-s3HN30_fw658&refer=http%3A%2F%2Fhbimg.b0.upaiyun.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1628560496&t=3aff566aeabec5a008fc9f3cb98ff452","2.jpg");
TestCallable t3= new TestCallable("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fhbimg.b0.upaiyun.com%2F9dae719a44088488ef29c515e9d9ae15f9e8a0ae816b-s3HN30_fw658&refer=http%3A%2F%2Fhbimg.b0.upaiyun.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1628560496&t=3aff566aeabec5a008fc9f3cb98ff452","3.jpg");
//创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> r1 = ser.submit(t1);
Future<Boolean> r2 = ser.submit(t2);
Future<Boolean> r3 = ser.submit(t3);
//获取结果
Boolean rs1 = r1.get();
Boolean rs2 = r2.get();
Boolean rs3 = r3.get();
System.out.println(rs1);
System.out.println(rs2);
System.out.println(rs3);
//关闭服务
ser.shutdown();
}
}
//下载器
class webDownloader{
//下载方法
public void downloader(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常,downloader方法出现问题");
}
}
}
静态代理
/**
* 静态代理
* 总结:
* 1、真实对象和代理对象都要实现同一个接口
* 2、代理对象要代理真实对象
*
* 优点:
* 代理对象可以做很多真实对象做不了的事情
* 真实对象可专注做自己能做的事
*/
public class StaticProxy {
public static void main(String[] args) {
// You you = new You();
// WeddingCompany wedCom = new WeddingCompany(you);
//实现Runnable接口,run()方法
new Thread(()-> System.out.println("我爱你")).start();
new WeddingCompany(new You()).HappyMarry();
WeddingCompany wedCom = new WeddingCompany(new You());
wedCom.HappyMarry();
}
}
interface Marry{
void HappyMarry();
}
//真实角色
class You implements Marry{
public void HappyMarry(){
System.out.println("秦老师要结婚了,超开心");
}
}
//代理角色,帮助结婚
class WeddingCompany implements Marry{
//代理谁--->真实目标角色
private Marry target;
public WeddingCompany(Marry target) {
this.target = target;//真实对象
}
public void HappyMarry(){
before();
this.target.HappyMarry();
after();
}
private void after() {
System.out.println("结婚之后,收尾款");
}
private void before() {
System.out.println("结婚之前,布置现场");
}
}
lambda表达式
- 避免匿名内部类定义过多
- 实质属于函数式编程
- 更简洁
【函数式接口】
- 只包含唯一一个抽象方法
- 可用lambda表达式来创建该接口的对象
/**
* 推导lambda表达式
*/
public class TestLambda1 {
//3、静态内部类
static class Like2 implements ILike{
@Override
public void lambda() {
System.out.println(" I like lambda2");
}
}
public static void main(String[] args) {
ILike like = new Like1();
like.lambda();
like = new Like2();
like.lambda();
//4、局部内布列
class Like3 implements ILike{
@Override
public void lambda() {
System.out.println(" I like lambda3");
}
}
like = new Like3();
like.lambda();
//5、匿名内部类,没有类的名称,必须借助接口或父类
like = new ILike(){
public void lambda(){
System.out.println(" I like lambda4");
}
};
like.lambda();
//6、用lambda表达式简化
like = () ->{
System.out.println(" I like lambda5");
};
like.lambda();
}
}
//1、定义一个函数式接口
interface ILike{
void lambda();
}
//2、实现类
class Like1 implements ILike{
@Override
public void lambda() {
System.out.println(" I like lambda1");
}
}
public class TestLambda2 {
public static void main(String[] args) {
ILove love = (int a)-> {
System.out.println(" i love you --->"+a);
};
love.love(520);
}
}
interface ILove{
void love(int a);
}
lambda表达式的简化
public class TestLambda2 {
public static void main(String[] args) {
//lambda表达式简化
ILove love = (int a,int b)-> {
System.out.println(" i love you --->"+a);
};
//简化1:去掉参数类型
love = (a,b)-> {
System.out.println(" i love you --->"+a);
};
//简化2:简化括号
love = (a,b) -> {
System.out.println(" i love you --->"+a);
};
//简化3:去掉花括号
love = (a,b) -> System.out.println(" i love you --->"+a);
/**
* 总结:
* 前提是函数式接口!!!
* lambda表达式中的方法体或代码块只能有一行代码时才能简化为一行,否则用用代码块包裹
* 多个参数类型也可以去掉,要去掉都去掉,必须加括号
*/
love.love(13,14);
}
}
interface ILove{
void love(int a,int b);
}
线程的五大状态
【创建】—{【阻塞】—【就绪】—【运行】(顺序不固定)}—【死亡】
方法 | 说明 |
---|---|
setPriority (int new Priority) | 更改线程的优先级 |
static void sleep(long millis) | 在指定的毫秒数内让当前正在执行的线程休眠 |
void join() | 等待该线程终止 |
static void yield() | 暂停当前正在执行的线程对象,并执行其他线程 |
void interrupt() | 中断线程(慎用) |
boolean isAlive() | 测试线程是否处于活动状态 |
线程停止
**
* 测试停止线程
* 1、建议线程正常终止--->利用次数,不建议死循环
* 2、建议使用标志位--->设置一个标志位
* 3、不要使用stop或destory等过时或JDK不建议使用的方法
*/
public class TestStop implements Runnable{
//1、设置一个标志位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while(flag){
System.out.println("run...Thread"+i++);
}
}
//2、设置一个公开的方法改变标志位,停止线程
public void stop(){
this.flag = false;
}
public static void main(String[] args) {
TestStop testStop = new TestStop();
new Thread(testStop).start();
for (int i = 0; i < 100; i++) {
System.out.println("main ---"+i);
if (i == 90){
//调用stop方法切换标志位,停止线程
testStop.stop();
System.out.println("线程该停止了");
}
}
}
}
线程休眠 sleep
【注意】
- sleep(时间)指定当前线程阻塞的毫秒数;
- sleep存在异常InterruptedException;
- sleep时间达到后线程进入就绪状态;
- sleep可以模拟网络延时,倒计时等。
- 每一个对象都有一个锁,sleep不会释放锁;
/**
* 模拟网络延时
*/
public class TestSleep2 {
public static void main(String[] args) {
//打印系统当前时间
Date startTime = new Date(System.currentTimeMillis());//获取系统当前时间
while(true){
try {
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
startTime = new Date(System.currentTimeMillis());//获取系统当前时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//模拟倒计时
public static void tenDown() throws InterruptedException {
int num = 10;
while(true){
Thread.sleep(1000);
System.out.println(num--);
if (num <= 0){
break;
}
}
}
}
线程礼让 yield
/**
* 测试礼让
* 礼让不一定成功
* 只提出礼让的意愿,是否真的礼让由CPU决定
*/
public class TestYield {
public static void main(String[] args) {
MyYield myYield = new MyYield();
new Thread(myYield,"a").start();
new Thread(myYield,"b").start();
}
}
class MyYield implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"线程开始执行");
Thread.yield();//礼让
System.out.println(Thread.currentThread().getName()+"线程结束执行");
}
}
线程插队 join
/**
* 测试join方法
* 插队
*/
public class TestJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("线程vip来了---"+i);
}
}
public static void main(String[] args) throws InterruptedException {
//启动我们的线程
TestJoin testJoin = new TestJoin();
Thread thread = new Thread(testJoin);
thread.start();
//主线程
for (int i = 0; i < 100; i++) {
if (i == 20){
thread.join();//插队
}
System.out.println("main---"+i);
}
}
}
Thread.state
- new
- runnable
- blocked
- waiting
- timed_waiting
- terminated
/**
* 观察测试线程状态
*/
public class TestState {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()->{
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("//");
});
//观察状态
Thread.State state = thread.getState();
System.out.println(state);//new
//观察启动后
thread.start();//启动线程
state = thread.getState();
System.out.println(state);//runnable
while(state != Thread.State.TERMINATED){//只要线程不终止,就一直输出状态
Thread.sleep(100);
state = thread.getState();//更新线程状态
System.out.println(state);//输出状态
}
}
}
线程的优先级
Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行。
线程的优先级用数字表示,范围从1~10.
- Thread.MIN_PRIORITY = 1;
- Thread.MAX_PRIORITY = 10;
- Thread.NORM_PRIORITY = 5;
- 改变或获取优先级:getPriority() . setPriority(int xxx)
【优先级低只是意味着获得调度的概率低,并不是优先级低就不会被先调用甚至不被调用】
/**
* 测试线程的优先级
*/
public class TestPriority {
public static void main(String[] args) {
//主线程的默认优先级
System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());
MyPriority myPriority = new MyPriority();
Thread t1 = new Thread(myPriority);
Thread t2 = new Thread(myPriority);
Thread t3 = new Thread(myPriority);
Thread t4 = new Thread(myPriority);
Thread t5= new Thread(myPriority);
//先设置优先级,再启动
t1.start();
t2.setPriority(1);
t2.start();
t3.setPriority(3);
t3.start();
t4.setPriority(Thread.MAX_PRIORITY);
t4.start();
t5.setPriority(Thread.MIN_PRIORITY);
t5.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());
}
}
守护线程daemon
- 线程分为用户线程和守护线程
- 虚拟机必须确保用户线程执行完毕
- 虚拟机不用等待守护线程执行完毕,如,后台记录操作日志,监控内存,垃圾回收等待
/**
* 测试守护线程
* 上帝 守护 你
*/
public class TestDaemon {
public static void main(String[] args) {
God god = new God();
You you = new You();
Thread t1 = new Thread(god);
t1.setDaemon(true);//默认false,表示用户线程,正常线程都是用户线程
t1.start();//上帝 守护线程启动
Thread t2= new Thread(you);
t2.start(); //你 用户线程启动
}
}
//上帝
class God implements Runnable{
@Override
public void run() {
while(true){
System.out.println("上帝保佑着你");
}
}
}
//你
class You implements Runnable{
@Override
public void run() {
for (int i = 0; i < 365; i++) {
System.out.println("你一生都开心地活着");
}
System.out.println("===goodbye world===");
}
}
线程同步——等待机制
三个不安全案例
买票
/**
* 不安全的买票
* 线程不安全
*/
public class UnsafeBuyTicked {
public static void main(String[] args) {
BuyTicket station = new BuyTicket();
new Thread(station,"per1").start();
new Thread(station,"per2").start();
new Thread(station,"per3").start();
}
}
class BuyTicket implements Runnable{
//票
private int ticketNums = 10;
boolean flag = true;//外部停止方式
@Override
public void run() {
//买票
while(flag){
buy();
}
}
private void buy(){
//判断是否有票
if (ticketNums <= 0){
flag = false;
return;
}
//模拟延时
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//买票
System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNums--+"张票");
}
}
取钱
/**
* 不安全的取钱
* 两个人去银行取钱
*/
public class UnsafeBank {
public static void main(String[] args) {
Account account = new Account(100,"结婚基金");
Drawing you = new Drawing(account,50,"你");
Drawing yourGirlfriend = new Drawing(account,100,"yourGirlfriend");
you.start();
yourGirlfriend.start();
}
}
//账户
class Account{
int money;//余额
String name;//卡名
public Account(int money, String name) {
this.money = money;
this.name = name;
}
}
//银行:模拟取款
class Drawing extends Thread{
//账户
Account account;
//取了多少钱
int drawingMoney;
//现在手里有多少钱
int nowMoney;
public Drawing(Account account,int drawingMoney,String name){
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
@Override
public void run() {
//判断有没有钱
if (account.money - drawingMoney < 0){
System.out.println(Thread.currentThread().getName()+"钱不够,取不了");
return;
}
//加大了问题发生的可能性
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额 = 余额 - 你取的钱
account.money = account.money - drawingMoney;
//你手里的钱
nowMoney = nowMoney + drawingMoney;
System.out.println(account.name+"账户余额为: "+account.money);
//this.getName() = Thread.currentThread.getName()
System.out.println(this.getName()+"的账户余额为: "+nowMoney);
}
}
不安全集合
/**
* 线程不安全的集合
*/
public class UnsafeList {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
三个案例加锁
买票
package com.cyf.syn;
/**
* 不安全的买票
* 线程不安全
*/
public class UnsafeBuyTicked {
public static void main(String[] args) {
BuyTicket station = new BuyTicket();
new Thread(station,"per1").start();
new Thread(station,"per2").start();
new Thread(station,"per3").start();
}
}
class BuyTicket implements Runnable{
//票
private int ticketNums = 10;
boolean flag = true;//外部停止方式
@Override
public void run() {
//买票
while(flag){
//模拟延时
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
buy();
}
}
//加synchronized,变成同步方法,锁的是this
private synchronized void buy(){
//判断是否有票
if (ticketNums <= 0){
flag = false;
return;
}
//买票
System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNums--+"张票");
}
}
取钱
package com.cyf.syn;
/**
* 不安全的取钱
* 两个人去银行取钱
*/
public class UnsafeBank {
public static void main(String[] args) {
Account account = new Account(100,"结婚基金");
Drawing you = new Drawing(account,50,"你");
Drawing yourGirlfriend = new Drawing(account,100,"yourGirlfriend");
you.start();
yourGirlfriend.start();
}
}
//账户
class Account{
int money;//余额
String name;//卡名
public Account(int money, String name) {
this.money = money;
this.name = name;
}
}
//银行:模拟取款
class Drawing extends Thread{
//账户
Account account;
//取了多少钱
int drawingMoney;
//现在手里有多少钱
int nowMoney;
public Drawing(Account account,int drawingMoney,String name){
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
@Override
public void run() {
//synchronized默认锁的是this,确保锁的目标正确,一般锁的是各个线程都要去操作的那个对象或资源
synchronized(account){
//判断有没有钱
if (account.money - drawingMoney < 0){
System.out.println(Thread.currentThread().getName()+"钱不够,取不了");
return;
}
//加大了问题发生的可能性
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额 = 余额 - 你取的钱
account.money = account.money - drawingMoney;
//你手里的钱
nowMoney = nowMoney + drawingMoney;
System.out.println(account.name+"账户余额为: "+account.money);
//this.getName() = Thread.currentThread.getName()
System.out.println(this.getName()+"的账户余额为: "+nowMoney);
}
}
}
安全的集合
package com.cyf.syn;
import java.util.ArrayList;
import java.util.List;
/**
* 线程不安全的集合
*/
public class UnsafeList {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
synchronized(list){
list.add(Thread.currentThread().getName());
}
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
JUC安全类型的集合
package com.cyf.syn;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* 测试JUC安全类型的集合
*/
public class TestJUC {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
同步方法和同步块
【并发】多个线程访问同一个对象
【解决方法】队列 + 锁
由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题。为了保证数据在方法中被访问时的正确性,
在访问时加入锁机制。synchronized当一个线程获得对象的排它锁,独占资源﹐其他线程必须等待,使用后释放锁即可。
由于我们可以通过private关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是synchronized
关键字,它包括两种用法:【synchronized方法】和【synchronized 块】。
同步方法:public synchronized void method(int args)
synchronized方法控制对“对象”的访问,每个对象对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则
线程会阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行;若将一个大的方法
申明为synchronized将会影响效率。
【存在以下问题】
-
方法里面需要修改的内容才需要锁,只读不需要锁
-
一个线程持有锁会导致其他所有需要此锁的线程挂起;
-
在多线程竞争下,加锁、释放锁会导致比较多的上下文切换和调度延时,引起性能问题;
-
如果一个优先级高的线程等待一个优先级低的线程释放锁会导致优先级倒置,引起性能倒置问题;
同步块:synchronized((Obj )
Obj称之为同步监视器,Obj可以是任何对象,但是推荐使用共享资源作为同步监视器
同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this ,就是这个对象本身﹐或者是class。同步监视器的执行过程
- 第一个线程访问,锁定同步监视器,执行其中代码;
- 第二个线程访问,发现同步监视器被锁定,无法访问;
- 第一个线程访问完毕,解锁同步监视器;
- 第二个线程访问,发现同步监视器没有锁,然后锁定并访问;
死锁
多个线程各自占有一些共享资源﹐并且互相等待其他线程占有的资源才能运行,而导致两个或者多个线程都在等待对方释放资源,都停止
执行的情形,某一个同步块同时拥有“两个以上对象的锁”时,就可能会发生“死锁”的问题。
【产生死锁的四个必要条件】
- 互斥条件:一个资源每次只能被一个进程使用
- 请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放
- 不剥夺条件:进程已获得的资源,在未使用完之前不能强行剥夺
- 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系
package com.cyf.syn;
/**
* 死锁:多个线程互相锁定对方需要的资源,形成僵持
*/
public class DeadLock {
public static void main(String[] args) {
Makeup girl1 = new Makeup(0,"灰姑娘");
Makeup girl2 = new Makeup(1,"白雪公主");
girl1.start();
girl2.start();
}
}
//口红
class LipStick{
}
//镜子
class Mirror{
}
//化妆
class Makeup extends Thread{
//需要的资源都只有一份,用static来保证
static LipStick lipStick = new LipStick();
static Mirror mirror = new Mirror();
int choice;//选择
String girlName;//要化妆的人
Makeup(int choice,String girlName){
this.choice = choice;
this.girlName = girlName;
}
@Override
public void run() {
//化妆
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//化妆,互相持有对方的锁,就是需要拿到对方的资源
private void makeup() throws InterruptedException {
if (choice == 0){
synchronized(lipStick){//获得口红的锁
System.out.println(this.girlName+"获得口红的锁");
Thread.sleep(1000);
}
synchronized(mirror){//1s后获得镜子的锁
System.out.println(this.girlName+"获得镜子的锁");
}
}else{
synchronized(mirror){//获得口红的锁
System.out.println(this.girlName+"获得镜子的锁");
Thread.sleep(2000);
}
synchronized(lipStick){//2s后获得口红的锁
System.out.println(this.girlName+"获得口红的锁");
}
}
}
}
Lock锁
从JDK5开始, Java提供了更强大的线程同步机制——通过显式定义同步锁对象来实现同步。同步锁使用Lock对象;
java.util.concurrent.locks.Lock接口是控制多个线程对共享资源进行访问的工具。锁提供了对共享资源的独占访问,每次只能有一个线程
对Lock对象加锁,线程开始访问共享资源之前应先获得Lock对象。
【可重入锁】ReentrantLock类实现了Lock,它拥有与synchronized相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是
ReentrantLock,可以显式加锁、释放锁。
package com.cyf.senior;
import java.util.concurrent.locks.ReentrantLock;
/**
* 测试Lock锁
*/
public class TestLock {
public static void main(String[] args) {
TestLock2 testLock2 = new TestLock2();
new Thread(testLock2).start();
new Thread(testLock2).start();
new Thread(testLock2).start();
}
}
class TestLock2 implements Runnable{
int ticketNums = 10;
//定义lock锁
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while(true){
try{
lock.lock();//加锁
if(ticketNums > 0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNums--);
}else{
break;
}
}finally{
lock.unlock();//解锁
}
}
}
}
synchronized 与Lock 的对比
- Lock是显式锁(手动开启和关闭锁,别忘记关闭锁) synchronized是隐式锁,出了作用域自动释放
- Lock只有代码块锁,synchronized有代码块锁和方法锁
- 使用Lock锁,JVM将花费较少的时间来调度线程,性能更好。扩展性更好(提供更多的子类)
【优先使用顺序】
Lock > 同步代码块(已经进入了方法体,分配了相应资源) > 同步方法(在方法体之外)