setDaemon(true);//设置为守护线程,默认false表示的是用户线程,正常的线程都是用户线程。。
举例:上帝是守护线程,你是用户线程,在你活着的36500天里上帝一直守护你,直到你死了
//测试守护线程
//上帝守护你
public class TestDaemon {
public static void main(String[] args) {
God god =new God();
You you =new You();
Thread thread =new Thread(god);
thread.setDaemon(true);//设置为守护线程,默认false表示的是用户线程,正常的线程都是用户线程。。
thread.start();//上帝守护线程启动
new Thread(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("====goodbye!world!====");
}
}
并发:同一个对象被多个线程同时操作。例:上万人抢100张票,两个银行同时取钱
线程同步形成条件:队列+锁
线程不安全实例:
抢车票问题:多个线程强盗同一张票,还会出现-1的情况
//不安全的买票
//线程不安全,有负数
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTiket station = new BuyTiket();
new Thread(station,"苦逼的我").start();
new Thread(station,"牛逼的你").start();
new Thread(station,"可恶的黄牛党").start();
}
}
class BuyTiket implements Runnable{
//票
private int ticketNums = 10;
boolean flag = true;//外部停止方式
@Override
public void run() {
//买票
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void buy() throws InterruptedException {
//判断是否有票
if(ticketNums<=0){
flag = false;
return;
}
//模拟延时
Thread.sleep(100);
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}
//不安全的取钱
//两个人去银行取钱,账户
public class UnsafeBank {
public static void main(String[] args) {
//账户
Accout accout = new Accout(100,"结婚基金");
Drawing you = new Drawing(accout,50,"你");
Drawing girlFriend = new Drawing(accout,100,"girlFriend");
you.start();
girlFriend.start();
}
}
//账户
class Accout{
int money;//余额
String name;//卡名
public Accout(int money, String name) {
this.money = money;
this.name = name;
}
}
//银行:模拟取款
class Drawing extends Thread{
Accout accout;//账户
//取了多少钱
int drawingMoney;
//现在手里有多少钱
int nowMoney;
public Drawing(Accout accout,int drawingMoney,String name){
super(name);
this.accout = accout;
this.drawingMoney = drawingMoney;
}
//取钱
@Override
public void run() {
//判断有没有钱
if(accout.money - drawingMoney < 0){
System.out.println(Thread.currentThread().getName()+"钱不够,取不了");
return;
}
//sleep:可以放大问题的发生性
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额 = 余额 - 你取的钱
accout.money = accout.money - drawingMoney;
//你手里的钱
nowMoney = nowMoney + drawingMoney;
System.out.println(accout.name+"余额为:"+accout.money);
//Thread.currentThread().getName()=this.getName()
System.out.println(this.getName()+"手里的钱"+nowMoney);
}
}
多线程给集合赋值问题:
多个线程给集合赋值时会导致赋值重复,导致赋值成功和预期数量和预期不同
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(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-AIJgE0S1-1590753934396)(C:\Users\p0151964\Desktop\集合赋值问题3.png)]
方法里需要修改的内容才需要锁,锁的太多浪费资源
*锁的对象是需要增删改查的对象
针对上边三个线程问题加锁让线程安全:
买票问题
//synchronized 同步方法,锁的是this
private synchronized void buy() throws InterruptedException {
//判断是否有票
if(ticketNums<=0){
flag = false;
return;
}
取钱问题:
取钱问题:
public void run() {
//锁的对象就是变化的量,需要增删改的对象
synchronized (accout){
//判断有没有钱
if(accout.money - drawingMoney < 0){
System.out.println(Thread.currentThread().getName()+"钱不够,取不了");
return;
}
//sleep:可以放大问题的发生性
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额 = 余额 - 你取的钱
accout.money = accout.money - drawingMoney;
//你手里的钱
nowMoney = nowMoney + drawingMoney;
System.out.println(accout.name+"余额为:"+accout.money);
//Thread.currentThread().getName()=this.getName()
System.out.println(this.getName()+"手里的钱"+nowMoney);
}
}
集合赋值问题:
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
synchronized (list){
list.add(Thread.currentThread().getName());
}
}).start();
}
JUC安全类型集合
CopyOnWriteArrayList list = new CopyOnWriteArrayList();
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 < 10200; 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.test.syn;
//死锁:多个线程互相抱着对方需要的资源,然后形成僵持。
public class DeadLock {
public static void main(String[] args) {
Makeup g1 = new Makeup(0,"灰姑娘");
Makeup g2 = new Makeup(1,"白雪公主");
new Thread(g1).start();
new Thread(g2).start();
}
}
//口红
class Lipstick{
}
//镜子
class Mirror{
}
class Makeup extends Thread {
//需要的资源只有一份,用static来保证只有一份
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choice;//选择
String girlNmae;//使用化妆品的人
Makeup(int choice, String girlNmae) {
this.choice = choice;
this.girlNmae = girlNmae;
}
@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.girlNmae + "获得口红的锁");
Thread.sleep(1000);
synchronized (mirror) {//一秒钟后想获得镜子
System.out.println(this.girlNmae + "获得镜子的锁");
}
}
} else {
synchronized (mirror) {//获得镜子的锁
System.out.println(this.girlNmae + "获得镜子的锁");
Thread.sleep(2000);
synchronized (lipstick) {//一秒钟后想获得口红
System.out.println(this.girlNmae + "获得口红的锁");
}
}
}
}
}
执行结果:
解决办法:让其中一个人拿了一件东西使用后就放开锁
else {
synchronized (mirror) {//获得镜子的锁
System.out.println(this.girlNmae + "获得镜子的锁");
Thread.sleep(2000);
}//把下一个锁写在上一个锁的外面
synchronized (lipstick) {//一秒钟后想获得口红
System.out.println(this.girlNmae + "获得口红的锁");
}
}
执行结果:
上面列出了死锁的四个必要条件,我们只要想办法破其中的任意一个或多个条件就可以避免死锁发生。
用法:
class A{
private final ReentrantLock lock = new ReenTrantLock();
public void m(){
lock.lock();
try{
//保证线程安全的代码
}
finally{
lock.unlock();
//如果同步代码有异常,要将unlock()写入finally语句块
}
}
示例代码抢票系统:
package com.test.gaoji;
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 ticktNums = 10;
//定义lock锁
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true){
try {
lock.lock();//加锁
if(ticktNums > 0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticktNums--);
}else{
break;
}
}finally {
//解锁
lock.unlock();
}
}
}
}
synchronized与Lock的对比
Lock是显式锁(手动开启和关闭锁,别忘了关闭锁)synchronized是隐式锁,出了作用域自动释放。
Lock只有代码块锁,synchronized有代码块锁和方法锁
使用Lock锁,JVM将花费较少的时间来调度线程,性能更好,并且具有更好的扩展性(提供更多的子类)
优先使用顺序:
Lock > 同步代码块(已经进入了方法体,分配了相应资源)>同步方法(在方法体之外)
线程通信:
这是一个线程同步问题,生产者和消费者共享了同一个资源,并且生产者和消费者之间互相依赖,互为条件。
注意:均是Object类的方法,都只能在同步方法或者同步代码块中使用,否则会抛出异常IIIegalMonitorStateException
解决方式1:
并发协作模型“生产者/消费者模式”–>管程法
package com.test.gaoji;
//测试生产者消费者模型:利用缓冲区解决:管程法
import java.util.concurrent.SynchronousQueue;
//生产者,消费者,产品,缓冲区
public class TestPC {
public static void main(String[] args) {
synContainer container = new synContainer();
new Productor(container).start();
new Consumer(container).start();
}
}
//生产者
class Productor extends Thread{
synContainer container;
public Productor(synContainer container){
this.container = container;
}
//生产
public void run(){
for (int i = 1; i < 101; i++) {
container.push(new Chicken(i));
System.out.println("生产了第"+i+"只鸡");
}
}
}
//消费者
class Consumer extends Thread{
synContainer container;
public Consumer(synContainer container){
this.container = container;
}
//消费
public void run(){
for (int i = 1; i < 101; i++) {
System.out.println("消费了第--》"+container.pop().id+"只鸡");
}
}
}
//产品
class Chicken{
int id;
public Chicken(int id) {
this.id = id;
}
}
//缓冲区
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;
}
}
结果:
生产者将生产好的数据放入缓冲区,消费者从缓冲区拿出数据。
解决方式2:
com.text.demo2;
//测试生产者消费者问题2:信号灯法,标志位法
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 = 0;i < 20;i++){
if(i%2==0){
this.tv.paly("快乐大本营播放中");
}else{
this.tv.paly("抖音记录美好生活");
}
}
}
}
//消费者--》观众
class Watcher extends Thread{
TV tv;
public Watcher(TV tv){
this.tv= tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
tv.watch();
}
}
}
//产品--》节目
class TV{
//演员表演,观众等待
//观众观看,演员等待
String voice;//表演的节目
boolean flag = true;
//表演
public synchronized void paly(String voice){
if(!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演员表演了"+voice);
//通知观众观看
this.notifyAll();//通知唤醒
this.voice=voice;
this.flag=!this.flag;
}
//观看
public synchronized void watch(){
if(flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观看了:"+voice);
//通知演员表演
this.notifyAll();
this.flag=!this.flag;
}
}
背景:经常创建和销毁,使用量特别大的资源,比如并发情况的线程,对性能影响很大。
思路:提前创建好多个线程,放入线程池中,使用时直接获取,使用完放回线程池中。可以避免频繁的创建销毁,实现重复利用。类似生活中的公共交通工具。
好处:
JDK 5.0起提供了线程池相关API:ExecutorService和Executors
ExecutorService:真正的线程池接口。常见子类ThreadPoolExecutor
Executors:工具类,线程池的工厂类,用于创建并返回不同类型的线程池
示例:
package com.text.demo2;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//测试线程池
public class TextPool {
public static void main(String[] args) {
//1.创建服务,创建线程池
//newFixedThreadPool 参数为:线程池大小
ExecutorService service = Executors.newFixedThreadPool(10);
//执行
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
//2.关闭连接
service.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
package com.text.demo2;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
//回顾总结线程的创建
public class ThreadNew {
public static void main(String[] args) {
new MyThread1().start();
new Thread(new MyThread2()).start();
FutureTask<Integer> futureTask =new FutureTask<Integer>(new MyThread3());
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 MyThread1 extends Thread{
@Override
public void run() {
System.out.println("MyThread1");
}
}
//2.实现Runnable接口
class MyThread2 implements Runnable{
@Override
public void run() {
System.out.println("MyThread2");
}
}
//3.实现callable接口
class MyThread3 implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("MyThread3");
return 100;
}
}