1、线程概念
- 进程则是执行程序的一次执行过程,他是一个动态的概念。是系统资源分配的单位
- 通常在一个进程中可以包含若干个线程,当然一个进程中至少有一个线程,不然没有存在的意义
核心概念
- 对同一份资源操作时,会在资源抢夺问题,需要加入并发控制
- 每个线程在自己的工作内存交互,内存控制不当会造成数据不一致
- 线程会带来额外的开销,如CPU调度时间,并发控制开销
2、Thread
- 自定义线程继承Thread类
- 重写run方法,编写线程执行体
- 创建线程对象,调用start()方法启动线程
- 线程开启的方法,由cpu调度
//自定义一个类继承Thread类。重写run()方法,调用start()方法开启线程
public class TestThread1 extends Thread{
//重写run方法。编写方法体。
public void run(){
for (int i = 0; i < 10; i++) {
System.out.println("我在看代码!" + i);
}
}
public static void main(String[] args) {
//main线程。主线程
//创建一个TestThread对象
TestThread1 s1 = new TestThread1();
//调用start()方法开启线程
s1.start();
for (int i = 0; i < 200; i++) {
System.out.println("我在写程序!" + i);
}
}
}
- 导入
common-io-2、6
包,建立lib,复制进来,Add as… 下载图片使用
FileUtils.copyURLToFile( URL, File);
执行代码:
//练习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() {
WebDown webdown = new WebDown();
webdown.down(url,name);
System.out.println("下载了图片: " + name);
}
public static void main(String[] args) {
TestThread2 s1 = new TestThread2("https://ns-strategy.cdn.bcebos.com/ns-strategy/upload/fc_big_pic/part-00624-4015.jpg", "1.jpg");
TestThread2 s2 = new TestThread2("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3699354628,919100137&fm=26&gp=0.jpg", "2.jpg");
TestThread2 s3 = new TestThread2("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3052674593,1733917049&fm=26&gp=0.jpg", "3.jpg");
s1.run();
s2.run();
s3.run();
}
}
//下载器
class WebDown{
//下载方法
public void down(String url, String name){
try {
FileUtils.copyURLToFile(new URL(url), new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常,WebDown出现异常");
}
}
}
3、Runnable
- 实现接口
Runnable
具有多线程能力 - 启动线程:传入目标对象+Thread对象.start();
- 推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用
//自定义线程类:接口Runnable, 重写run方法,调用runnable接口类。start();
public class TestThread3 implements Runnable{
//重写run方法。编写方法体。
public void run(){
for (int i = 0; i < 10; i++) {
System.out.println("我在看代码!" + i);
}
}
public static void main(String[] args) {
//main线程。主线程
//通过ruannable对象来实现接口
TestThread1 s1 = new TestThread1();
//创建线程对象,通过线程对象来开启线程。调用start()方法开启线程
//Thread thread = new Thread(s1);
//thread.start();
new Thread(s1).start();
s1.start();
for (int i = 0; i < 200; i++) {
System.out.println("我在写程序!" + i);
}
}
}
获取线程名字
Thread.currentThread().getName();
买票简单问题:
public class TestThread4 implements Runnable {
private int ticketNumes = 10; //票数
public void run() {
while (true) {
if (ticketNumes <= 0) {
break;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "拿到了第" + ticketNumes-- + "张票");
}
}
public static void main(String[] args) {
TestThread4 ticket = new TestThread4();
new Thread(ticket, "小明").start();
new Thread(ticket, "小张").start();
new Thread(ticket, "帐篷").start();
}
}
4、Callable接口
- 需要返回值类型
- 好处:可以定义返回值,可以抛出异常
- 重写call方法,需要抛出异常
- 创建目标对象
TestCallable s1 = new TestCallable();
- 创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(3);
- 提交执行
Future<Boolean> re1 = ser.submit(s1);
- 获取结果
boolean r1 = re1.get();
- 关闭服务
ser.shutdownNow();
实现代码:
//练习Thread,实现多线程同步下载图片
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() {
WebDownLoad webdown = new WebDownLoad();
webdown.down(url,name);
System.out.println("下载了图片: " + name);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
//创建目标对象
TestCallable s1 = new TestCallable("https://ns-strategy.cdn.bcebos.com/ns-strategy/upload/fc_big_pic/part-00624-4015.jpg", "1.jpg");
TestCallable s2 = new TestCallable("https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3699354628,919100137&fm=26&gp=0.jpg", "2.jpg");
TestCallable s3 = new TestCallable("https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3052674593,1733917049&fm=26&gp=0.jpg", "3.jpg");
//创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> re1 = ser.submit(s1);
Future<Boolean> re2 = ser.submit(s2);
Future<Boolean> re3 = ser.submit(s3);
//获取结果
boolean r1 = re1.get();
boolean r2 = re1.get();
boolean r3 = re1.get();
//输出结果
System.out.println(r1);
System.out.println(r2);
System.out.println(r3);
}
}
//下载器
class WebDownLoad{
//下载方法
public void down(String url, String name){
try {
FileUtils.copyURLToFile(new URL(url), new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常,WebDown出现异常");
}
}
}
4、1静态代理模式
- 真实对象和代理对象都要实现同一接口,
- 代理对象要代理真实角色
- 好处:
1、代理对象可以做好真实对象做不了的事情。
2、真实对象在做自己的事情。
public class StaticProxy {
public static void main(String[] args) {
/*
My s2 = new My();
WeddingCompane s3 = new WeddingCompane(s2);
s1.HappyMarry();
*/
new Thread(()-> System.out.println("我爱你")).start(); //这两个特别像。
new WeddingCompane(new My()).HappyMarry();
}
}
//定义一个接口
interface Marry{
void HappyMarry();
}
//定义一个真实类,实现接口。
class My implements Marry{
@Override
public void HappyMarry() {
System.out.println("冰凝要结婚了!冰先生超开心");
}
}
//定义一个代理对象,实现接口
class WeddingCompane implements Marry{
private Marry tagger; //定义一个对象,
public WeddingCompane(Marry tagger) { //构造方法传入参数
this.tagger = tagger;
}
@Override
public void HappyMarry() {
befor();
tagger.HappyMarry(); //用于实现真实对象的方法
after();
}
private void after() {
System.out.println("结婚后,要交婚庆钱了!");
}
private void befor() {
System.out.println("结婚前,要去找婚庆公司!");
}
}
4、2龟兔赛跑
//龟兔赛跑
public class Race implements Runnable{
private String sWing;
@Override
public void run() { //线程
for (int i = 0; i <= 100; i++) {
//让兔子睡一觉,保证乌龟赢
if(Thread.currentThread().getName().equals("兔子") && i%10==0){
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
//判断是否有选手赢得比赛
boolean game = gameOver(i);
System.out.println(Thread.currentThread().getName() + "跑了" + i +"步");
if(game == true){
break;
}
}
}
//判断比赛是否结束
public boolean gameOver(int i){
if(sWing != null){
return true;
}if (i >= 100){
sWing = Thread.currentThread().getName();
System.out.println(Thread.currentThread().getName() + "赢了比赛");
return true;
}
return false;
}
public static void main(String[] args) {
Race s1 = new Race();
new Thread(s1,"兔子").start();
new Thread(s1,"乌龟").start();
}
}
5、Lamda表达式
- 希腊字母表中排序第是一位的字母,英文名称为
Lambda
- 避免匿名内部类定义过多
- 去掉了没有意义的代码,只留下核心
- 可以让代码变的很简洁
理解Function Interface(函数式接口)是学习Java8 Lambda表达式关键所在
1、定义:任何接口,如果只包含唯一一个抽象方法,那么它就是函数式接口
public interface Runnable{
public abstract void run();
}
对于函数式接口,我们通过lambda表达式来创建该接口的对象
TestLambda1
public class TestLambda1 {
//2、实现一个静态成员内部类
static class Like2 implements ILike{
@Override
public void Like() {
System.out.println("这是Like2");
}
}
public static void main(String[] args) {
ILike like1 = new Like1();
like1.Like();
//TestLambda1.Like2 s = new TestLambda1().new Like2(); 成员内部类定义方法
like1 = new Like2();
like1.Like();
//3、实现一个局部内部类
class Like3 implements ILike{
@Override
public void Like() {
System.out.println("这是Like3");
}
}
like1 = new Like3();
like1.Like();
//4、匿名内部类
like1 = new ILike() {
@Override
public void Like() {
System.out.println("这是一个匿名内部类! I like lambda4");
}
};
like1.Like();
//6、使用lambda表达式来编写
like1 = ()->{
System.out.println("这是一个匿名内部类! I like lambda5");
};
like1.Like();
}
}
//实现一个接口
interface ILike{
void Like();
}
//1、实现一个外部类,并调用接口
class Like1 implements ILike{
@Override
public void Like() {
System.out.println("这是Like1");
}
}
TestLambda2
public class TestLambda2 {
//内部类
static class Love1 implements ILove{
@Override
public void love(int a) {
System.out.println("I love1 you" + a);
}
}
public static void main(String[] args) {
ILove love = null;
//局部内部类
class Love2 implements ILove{
@Override
public void love(int a) {
System.out.println("I love you" + a);
}
}
//匿名内部类 第一种
/*love = new ILove() {
@Override
public void love(int a) {
System.out.println("I love you" + a);
}
};*/
//第二种表达方式
/*love = (int a)->{
System.out.println("I love you" + a);
};*/
//第三种表达方式
//love = a -> { System.out.println("I love you" + a); };
//第四种表达方式 ,只能有一行代码的情况下。
love = a -> System.out.println("I love you" + a);
love.love(520);
//
}
}
interface ILove{
void love(int a);
}
//外部类
class Love implements ILove{
@Override
public void love(int a) {
System.out.println("I love you" + a);
}
}
总结
- lambda表达式只能有一行代码的情况下才能简化为一行,如果有多行,花括号不能去掉。
- 前提:必须是函数式接口
- 如果有几个形式参数,那么都去变量类型,要不都不去掉。
6、线程常见方法
6、1线程停止
- 建议线程正常停止–>利用次数,不建议死循环
- 建议使用标志位–>设置一个标志位
- 不要使用stop和destory等过时或jdk不建议使用的方法
public class TestStop implements Runnable{
//建立一个标示位
private boolean fall = true;
@Override
public void run() {
int i = 0;
while (fall){
System.out.println("正在运行线程 " + i++);
}
}
//设置一个公共停止的方法
public void stop(){
this.fall = false;
}
public static void main(String[] args) {
TestStop testStop = new TestStop();
new Thread(testStop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main开始执行了" + i);
if(i == 900){
testStop.stop();
System.out.println("该线程停止了");
}
}
}
}
6、2线程休眠
sleep
指定当前线程阻塞的毫秒数sleep
存在异常interruptedException
sleep
时间达到后线程进入就绪状态sleep
可以模拟网络延时,倒计时等- 每一个对象都有一个锁,sleep不会释放锁。
模拟网络延时,可以放大问题的发生
public class TestSleep1 implements Runnable {
private int ticketNumes = 10; //票数
public void run() {
while (true) {
if (ticketNumes <= 0) {
break;
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "拿到了第" + ticketNumes-- + "张票");
}
}
public static void main(String[] args) {
TestSleep1 ticket = new TestSleep1();
new Thread(ticket, "小明").start();
new Thread(ticket, "小张").start();
new Thread(ticket, "帐篷").start();
}
}
public class TestSleep2 {
public static void main(String[] args) {
//打印当前时间
/*Date time1 = new Date(System.currentTimeMillis());
while (true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(new SimpleDateFormat("HH:mm:ss").format(time1));
time1 = new Date(System.currentTimeMillis());//更新当期时间
}*/
try {
turnDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//倒计时
public static void turnDown() throws InterruptedException {
int ticket = 10;
while (true){
Thread.sleep(1000);
System.out.println("-->" + ticket--);
if(ticket <= 0){
break;
}
}
}
}
6、3线程礼让
yield()
:让当前正在执行的线程暂停,但不阻塞。将线程从运行状态转为就绪状态,让cpu重新调度,礼让不一定成功!看cpu心情
public class TestYield {
public static void main(String[] args) {
Yield1 yield1 = new Yield1();
new Thread(yield1,"小明").start();
new Thread(yield1,"小张").start();
}
}
class Yield1 implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "线程开始运行");
Thread.yield();
System.out.println(Thread.currentThread().getName() + "线程结束运行");
}
}
6、4观测线程状态
Thread.State state = thread.getState();
线程终端或结束,一旦进入死亡状态,就不能再次启用。
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(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("\\\\\\\\");
});
//观察线程状态
Thread.State state = thread.getState();
System.out.println("new");
System.out.println(state);
//启动线程
thread.start();
//在测试线程状态
state = thread.getState();
System.out.println(state);
while (state != Thread.State.TIMED_WAITING){ //只要线程不终止,就继续执行
Thread.sleep(100); //设置休眠时间
state = thread.getState(); //刷新线程状态。
System.out.println(state);
}
}
}
6、5线程强制执行
join
合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞- 可以想象为插队
public class TestJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("线程来了" + 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 < 500; i++) {
if(i == 100) {
thread.join(); //插队
}
System.out.println("main" + i);
}
}
}
6、6线程优先级
- java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级了决定应该调度哪个线程来执行
- 优先级用数字表示,从1-10
Thread.MIN_PRIORITY=1;
Thread.NORM_PRIORITY=5;
Thread.MAX_PRIORITY=10;
- 使用以下方式改变或获取优先级
setPriority();
getPriority();
注:优先级低只能意味着获取调度的概率低,并不是优先级低就不会被调度了,这都是看cpu的调度
public class TestPriority {
public static void main(String[] args) {
MyPriority myPriority = new MyPriority();
//获取主线程的优先级;
System.out.println(Thread.currentThread().getName()+ " --> " + Thread.currentThread().getPriority());
Thread t1 = new Thread(myPriority,"s1");
Thread t2 = new Thread(myPriority,"s2");
Thread t3 = new Thread(myPriority,"s3");
Thread t4 = new Thread(myPriority,"s4");
Thread t5 = new Thread(myPriority,"s5");
//设置线程优先级进行调度
t1.setPriority(Thread.MIN_PRIORITY); //优先级设为1
t1.start();
t2.setPriority(Thread.NORM_PRIORITY); //优先级设为5
t2.start();
t3.setPriority(Thread.MAX_PRIORITY); //优先级设为10
t3.start();
t4.setPriority(3);
t4.start();
t5.setPriority(6);
t5.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());
}
}
6、7守护线程
- 线程分为用户线程和守护线程,
- 虚拟机必须确保用户线程执行完毕
- 虚拟机不用管守护线程这些完毕
- 如:后台记录操作目录,监控内存,垃圾回收等
//上帝守护你
public class TestDaemon {
public static void main(String[] args) {
//定义上帝的线程
God god = new God();
Thread thread = new Thread(god);
thread.setDaemon(true); // 默认为flase是用户线程, 正常情况是用户线程。
thread.start();
//定义你的线程
new Thread(new You()).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 < 36500; i++) {
System.out.println("你一直开心的活着!");
}
System.out.println("===== Game over World!");
}
}
7、线程同步
并发:同一个对象被多个线程同时操作
- 处理多线程问题时,多个线程访问同一个对象,并且某些线程还想修改这个对象,这时候我们就需要线程同步,线程同步其实就是一种等待机制,多个需要访问此对象的线程进入这个对象的等待线程池形成队列,等待前面的线程池使用完毕,下一个线程再使用。
7、1锁机制
synchronized
:当一个线程获得对象的排它锁,独占资源,其它线程必须等待,使用后释放锁即可,存在问题
- 一个线程持有锁会导致其它所有需要此锁的线程挂起
- 在多锁竞争时,加锁,释放锁会导致比较多的上下文切换和调度延时,引起性能问题
- 如果一个优先级高的线程等待一个优先级低的线程,释放锁会导致优先级导致,引起性能问题。
不安全的买票
public class UnfateBuyTicket {
public static void main(String[] args) {
BuyTicket station = new BuyTicket();
new Thread(station,"黄牛党的我们").start();
new Thread(station,"积极向上的我们").start();
new Thread(station,"赶集市的我们").start();
}
}
class BuyTicket implements Runnable{
boolean flag = true; //停止线程使用
private int ticketNums = 10;//车票张数
@Override
public void run() {
//买票
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//synchronized 同步方法, 锁是本身
public void buy() throws InterruptedException {
//判断是否有票
if(ticketNums <= 0){
flag = false;
return;
}
Thread.sleep(100);
System.out.println(Thread.currentThread().getName() + "买到了第" + ticketNums--);
}
}
不安全的取钱
//两个人去银行取钱,账户
public class UnfateBank {
public static void main(String[] args) {
Account account = new Account("结婚基金",100);
Bank you = new Bank(account,50,"你");
Bank girlFriend = new Bank(account,80,"女朋友");
you.start();
girlFriend.start();
}
}
class Account{
String name; //卡名
int money; //卡里的钱
public Account(String name, int money) {
this.name = name;
this.money = money;
}
}
class Bank extends Thread{
Account account; //账号
int drawingMoney; //去了多少钱
int nowMoney; //现在手上的钱
//传入账号数据和取钱的数据
public Bank(Account account, int drawingMoney, String name) {
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
this.nowMoney = nowMoney;
}
@Override
public void run() {
if((account.money - drawingMoney) <= 0){
System.out.println(account.name + "钱不不够了!"+account.name+"卡里的钱还有" + account.money);
return;
}
try {
Thread.sleep(100); //sleep放大了线程的不安全性
} catch (InterruptedException e) {
e.printStackTrace();
}
account.money -= drawingMoney; //现在卡里的钱
nowMoney += drawingMoney;
System.out.println(account.name + "账号卡里余额为:" + account.money);
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(()->{
synchronized(list){
list.add(Thread.currentThread().getName());
}
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
7、2同步方法和同步快
synchronized
方法和synchronized
快
- 同步方法:
public sychronized void methos(){}
- 方法里面需要修改的内容才需要锁,锁的太多,浪费资源
- 同步快:
synchronized(obj){ }
obj
称为同步监视器- obj可以是任何对象,但是推荐使用共享资源作为同步监视器
- 同步方法中无需指定同步监视器,因为同步方法的同步监视器this,就是这个对象本身,或者class(反射中讲述)
不安全取钱改进
public class UnfateBank {
public static void main(String[] args) {
Account account = new Account("结婚基金",100);
Bank you = new Bank(account,50,"你");
Bank girlFriend = new Bank(account,80,"女朋友");
you.start();
girlFriend.start();
}
}
class Account{
String name; //卡名
int money; //卡里的钱
public Account(String name, int money) {
this.name = name;
this.money = money;
}
}
class Bank extends Thread{
Account account; //账号
int drawingMoney; //去了多少钱
int nowMoney; //现在手上的钱
//传入账号数据和取钱的数据
public Bank(Account account, int drawingMoney, String name) {
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
this.nowMoney = nowMoney;
}
@Override
public void run() {
/*
锁的是account。
锁的对象是变化的量
*/
synchronized (account){
//判断是否还有钱
if((account.money - drawingMoney) <= 0){
System.out.println(account.name + "钱不不够了!"+account.name+"卡里的钱还有" + account.money);
return;
}
try {
Thread.sleep(100); //sleep放大了线程的不安全性
} catch (InterruptedException e) {
e.printStackTrace();
}
account.money -= drawingMoney; //现在卡里的钱
nowMoney += drawingMoney;
System.out.println(account.name + "账号卡里余额为:" + account.money);
System.out.println(this.getName() + "手里还有" + nowMoney + "钱");
}
}
}
不安全买票改进
public class UnfateBuyTicket {
public static void main(String[] args) {
BuyTicket station = new BuyTicket();
new Thread(station,"黄牛党的我们").start();
new Thread(station,"积极向上的我们").start();
new Thread(station,"赶集市的我们").start();
}
}
class BuyTicket implements Runnable{
boolean flag = true; //停止线程使用
private int ticketNums = 10;//车票张数
@Override
public void run() {
//买票
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//synchronized 同步方法, 锁是本身
public synchronized void buy() throws InterruptedException {
//判断是否有票
if(ticketNums <= 0){
flag = false;
return;
}
Thread.sleep(100);
System.out.println(Thread.currentThread().getName() + "买到了第" + ticketNums--);
}
}
线程不安全的集合改进
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());
}
}
同步监视器执行过程
- 第一个线程访问,锁定同步监视器,并执行其中的代码
- 第二个线程访问,发现同步监视器被锁定,无法访问
- 第一个线程访问完毕,解锁同步监视器
- 第二个线程访问,发现同步监视器没有锁,然后锁定访问
7、3测试JUC安全类集合
- 测试JUC安全类集合:
CopyOnWriteArrayList
- 因为这个集合类本身同步,所以不需要定义所:
synchronized
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(3_000
);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
7、4死锁
某一个同步快同时拥有“两个以上对象的锁”时,就可能会发生“死锁”
的问题
产生死锁的四个必要条件
- 互斥条件:一个资源每次只能被一个进程使用
- 请求好保持条件:一个进程因请求资源而阻塞,对已获得的资源不放
- 不剥夺条件:进程已获得的资源,在未使用完之前,不能强行剥夺
- 循环等待条件:若干个进程之间形成一种头尾相接的循环等待关系
- 上面列出的四个必要条件,我们只要想办法破其中的任意一个或多个条件就可以避免死锁产生
/*
死锁:
某一个代码块拥有”两个以上对象的锁“时,就可能会发生死锁的现象
*/
public class TestDeadLock {
public static void main(String[] args) {
Makeup makeup = new Makeup(0,"白雪公主");
Makeup makeup1 = new Makeup(1,"灰姑娘");
makeup.start();
makeup1.start();
}
}
//口红
class Lipstick{
}
//镜子
class Mirror{
}
class Makeup extends Thread{
//需要的资源只有一份,用static来保证只有一份
static Lipstick lipstick = new Lipstick(); //口红
static Mirror mirror = new Mirror(); //镜子
int choice; //选择哪个
String name; //名字
Makeup(int choice,String name){
this.choice = choice;
this.name = name;
}
//化妆
public void run(){
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//化妆,互相持有对方的锁,就是拿到对方的资源
public void makeup() throws InterruptedException {
if(choice == 0){
synchronized (mirror){
System.out.println(this.name+"获得了镜子");
}
Thread.sleep(1000);
synchronized (lipstick){
System.out.println(this.name + "获得了口红");
}
}else {
synchronized (lipstick){
System.out.println(this.name+"获得了口红");
}
Thread.sleep(2000);
synchronized (mirror){
System.out.println(this.name + "获得了镜子");
}
}
}
}
8、Lock锁
- 从JDK5.0开始,Java提供了更强大的线程同步机制——通过显示定义同步锁对象来实现同步。同步锁使用lock对象充当
java.util.concurrent.locks.lock
接口是控制多个线程对共享资源进行访问的工具。锁提供了对共享资源的独占访问,每次只能有一个线程时lock对象加锁,线程开始访问共享资源之前应先获得lock对象。ReentranLock
类实现了Lock,它拥有与synchronized相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentranLock
,可以显示加锁、释放锁
private final ReentranLock lock = new ReentranLock();
public class TestReentrantLock {
public static void main(String[] args) {
Test2Ticket test2Ticket = new Test2Ticket();
new Thread(test2Ticket).start();
new Thread(test2Ticket).start();
new Thread(test2Ticket).start();
}
}
class Test2Ticket implements Runnable{
private 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是显示锁(手动开启和关闭锁,别忘记关闭锁)
synchronize
是隐式锁,出了作用域自动释放 - lock只有代码块锁,synchronized有代码块锁和方法锁
- 使用lock锁,JVM将花费较少的时间来调度线程,性能更好,并且具有更好的扩展性(提供更多的子类)
优先使用顺序
lock–>同步代码块(已经进入了方法体,分配了相应资源)–>同步方法(在方法体之外)
8、1线程通信
- Java提供了几个方法解决了线程之间的通信问题
- wait()表示线程一直等待,直到其他线程通知,与sleep不同,会释放锁
- wait(long timeout)指定等待的毫秒数
- notify()唤醒一个处于等待的线程
- notifyAll()唤醒同一个对象上所有调度wait()方法的线程,优先级高的线程优先调度
生产消费者问题
- 管程法:建立一个容器
//生产者消费者问题: 利用缓冲区解决:管程法
// 生产者 消费者 产品 缓冲区
public class TestPC {
public static void main(String[] args) {
SynContainer synContainer = new SynContainer();
new Productor(synContainer).start();
new Consumer(synContainer).start();
}
}
//生产者
class Productor extends Thread{
SynContainer synContainer;
public Productor(SynContainer synContainer) {
this.synContainer = synContainer;
}
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
synContainer.push(new Chicken(i));
System.out.println("生产了第-->" + i +"只鸡");
}
}
}
//消费者
class Consumer extends Thread{
SynContainer synContainer;
public Consumer(SynContainer synContainer) {
this.synContainer = synContainer;
}
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
System.out.println("消费了第-->" + synContainer.pop().num +"只鸡");
}
}
}
//产品
class Chicken{
int num;
public Chicken(int num) {
this.num = num;
}
}
//缓冲区
class SynContainer{
//需要一个容器
Chicken[] chickens = new Chicken[10];
//生产了多少个
int count = 0;
//生产者放入产品
public synchronized void push(Chicken chicken){
if(count == chickens.length){
//通知消费者,生产者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果没满,那么久继续生产
chickens[count] = chicken;
count++;
//可以通知消费者了
this.notifyAll();
}
//消费者消费
public synchronized Chicken pop(){
if(count == 0){
//通知生产者生产,消费者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果可以消费,则消费
count--;
Chicken chicken = chickens[count];
//吃完了,通知生产者生产
this.notifyAll();
return chicken;
}
}
- 信号灯法:建立一个标识符
public class TestPC2 {
public static void main(String[] args) {
TV tv = new TV();
new Player(tv).start();
new Watcher(tv).start();
}
}
//表演者
class Player extends Thread{
TV tv;
public Player(TV tv) {
this.tv = tv;
}
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
if(i%2==0){
this.tv.play("快乐大本营");
}else {
this.tv.play("爸爸去哪了");
}
}
}
}
//观看者
class Watcher extends Thread{
TV tv;
public Watcher(TV tv) {
this.tv = tv;
}
@Override
public void run() {
for (int i = 1; i <= 100; i++) {
this.tv.watch();
}
}
}
//产品-》节目
class TV{
//表演者表演,观众等待 T
//观众观看,表演者等待 F
String voice; //表演节目
boolean fale = true; //标识符
//表演
public synchronized void play(String voice){
if(!fale){
//表演者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("表演了什么"+voice);
//通知观众观看
this.notifyAll();
this.voice = voice;
this.fale = !this.fale;
}
//观看者
public synchronized void watch(){
if(fale){
//观看者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观看了什么" + this.voice);
//通知表演者表演
this.notifyAll();
this.fale = !this.fale;
}
}
8、2线程池
- 背景:经常创建和销毁、使用量特别大的资源,比如并发情况下的线程,对性能影响很大
- 思路:提前创好多个线程,放入线程池中,使用时直接获取,使用完放回线程池中,可以避免频繁创建销毁,实现重复利用,类似生活中的交通工具
- 好处
- 提高响应效率(减少了创建新线程的时间)
- 降低资源消耗(重复利用线程池中线程,不需要每次都创建)
- 便于线程管理()
corePoolSize:核心池大小
maximumPoolSize:最大线程数
keepAliveTime:线程没有任务时最多保持多长时间后会终止
使用线程池
- JDK5.0起提供了线程相关API:
EXcutorService
和Excecutor
- ExcutorService:真正的线程池接口常见子类
ThreadPoolExceutor
- void execute(Runnable command):执行任务/命令,没有返回值,一般用来执行Runnable
- Futuresubmit(Callabletask);
执行任务,没有返回值,一般又来执行Callable - void shutdown()关闭连接池
public class ThreadNew {
public static void main(String[] args) {
//创建继承的目标对象并执行
new Thread1().start();
//创建Runnable目标对象并执行。
/*
Thread2 thread2 = new Thread2();
new Thread(thread2).start();
*/
new Thread(new Thread2()).start();
//创建Callable的目标对象并执行
FutureTask<Integer> futureTask = new FutureTask<Integer>(new Thread3());
new Thread(futureTask).start();
try {
Integer integer = futureTask.get();
System.out.println(integer);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
//1、继承Thread
class Thread1 extends Thread{
@Override
public void run() {
System.out.println("Thread1");
}
}
//2、接口Runnable
class Thread2 implements Runnable{
@Override
public void run() {
System.out.println("Thread2");
}
}
//3、实现callable接口
class Thread3 implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("Thread3");
return 0;
}
}
- Executors:工具类,线程池的工厂类,用于创建并返回不同类型的线程池
- 创建服务
ExecutorService service = Executors.newFixedThreadPool(NThread:10);
- 执行
service.execute(new 接口类)
- 关闭连接池
service,shutdown()
public class TestPool {
public static void main(String[] args) {
MyThread myThread = new MyThread();
//1、创建服务
ExecutorService service = Executors.newFixedThreadPool(10);
//2、执行
service.execute(myThread);
service.execute(myThread);
service.execute(myThread);
service.execute(myThread);
//3、关闭线程池
service.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}