JavaSE自学笔记Real_008(多线程基础)
线程的优先级设置(priority)
线程的优先级用数字表示,范围是1到10(在范围之外会报错)
Thread.MIN_PRIORITY = 1
Thread.MAX_PRIORITY = 10
Thread.NORM_PRIORITY = 5
方法函数:
Thread.currentThread.getPriority();
对象名.setPriority();
//测试线程的优先级
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);
Thread t6 = new Thread(myPriority);
//设置线程的优先级
t1.start();
t2.setPriority(1);
t2.start();
t3.setPriority(4);
t3.start();
t4.setPriority(Thread.MAX_PRIORITY);
t4.start();
t5.setPriority(-1);
t5.start();
t6.setPriority(11);
t6.start();
}
}
class MyPriority implements Runnable{
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see Thread#run()
*/
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());
}
}
结果:
main-->5
Thread-3-->10
Thread-2-->4
Thread-0-->5
Thread-1-->1
Exception in thread "main" java.lang.IllegalArgumentException
at java.base/java.lang.Thread.setPriority(Thread.java:1141)
at com.ThreadLearn.Demo013.TestPriority.main(TestPriority.java:29)
Process finished with exit code 1
守护线程(daemon)
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,表示永华线程,true表示守护线程,正常的线程都是永华线程
thread.start(); //开启守护线程
new Thread(you).start();
}
}
//上帝
class God implements Runnable{
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see Thread#run()
*/
@Override
public void run() {
while(true){
System.out.println("上帝保佑你。");
}
}
}
//你
class You implements Runnable{
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see Thread#run()
*/
@Override
public void run() {
for (int i = 0; i < 35600; i++) {
System.out.println("活了" + i +"天");
}
System.out.println("===========GoodBye world!===================");
}
}
线程同步
并发问题:同一个对象被多个线程同时操作
由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问的冲突问题,为了保证数据在方法中的正确性,在访问时加入锁机制(synchronizrd),当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后始放锁即可,存在以下问题:
1、一个线程持有锁会导致其他所需要此锁的线程挂起
2、在多个线程竞争下,加锁,释放锁会导致比较多的上下文切换和调度延时,引起性能问题
3、如果一个有限级高的线程等待一个优先级低的线程始放==释放锁会导致优先级倒置,引起性能问题
三个不安全的案例
1、不安全的买票
//不安全的买票
//线程不安全,会出现数据紊乱,出现有人拿到同一张票以及出现有人拿到第0张票的情况,甚至拿到票的编号为负数吧
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket buyTicket = new BuyTicket();
new Thread(buyTicket, "张三").start();
new Thread(buyTicket, "李四").start();
new Thread(buyTicket, "黄牛").start();
}
}
class BuyTicket implements Runnable{
//票
private int ticketNums = 10;
boolean flag = true; //外部停止方式
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see Thread#run()
*/
@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(1000);
//买票
System.out.println(Thread.currentThread().getName() + "拿到" + ticketNums--);
}
}
结果:
张三拿到10
李四拿到8
黄牛拿到9
黄牛拿到7
李四拿到7
张三拿到7
张三拿到6
李四拿到6
黄牛拿到5
张三拿到4
黄牛拿到3
李四拿到3
张三拿到2
黄牛拿到0
李四拿到1
Process finished with exit code 0
2、不安全的取钱
//不安全的取钱
//两个人去银行取钱,账户
public class UnsafeBank {
public static void main(String[] args) {
//账户
Account account = new Account(100, "基金");
Drawing you = new Drawing(account, 50, "你");
Drawing girlFriend = new Drawing(account, 100, "girlFriend");
you.start();
girlFriend.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;
this.nowMoney = nowMoney;
}
//取钱
/**
* If this thread was constructed using a separate
* {@code Runnable} run object, then that
* {@code Runnable} object's {@code run} method is called;
* otherwise, this method does nothing and returns.
* <p>
* Subclasses of {@code Thread} should override this method.
*
* @see #start()
* @see #stop()
* @see #Thread(ThreadGroup, Runnable, String)
*/
@Override
public void run() {
//判断有没有钱
if(account.money - drawingMoney < 0){
System.out.println(Thread.currentThread().getName() + "已经没钱了");
return;
}
//sleep可以放大问题的发生性
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额=余额-取的钱
account.money = account.money - drawingMoney;
//你手里的钱
nowMoney = nowMoney+drawingMoney;
System.out.println(account.name+"的余额为:"+account.money);
//Thread.currentThread().getName() = this.getName()
System.out.println(this.getName()+"手里的钱为:"+nowMoney);
}
}
结果:
基金的余额为:50
基金的余额为:-50
你手里的钱为:50
girlFriend手里的钱为:100
Process finished with exit code 0
3、不安全的集合
import java.util.ArrayList;
//线程不安全的集合
public class UnsafeList {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
System.out.println(list.size());
}
}
结果:
9993 //正确结果应该为10000
Process finished with exit code 0
线程同步的方法:
由于我们可以通过private关键字来保证数据对象只能被方法访问。所以我们只需要针对方法提出一种机制,这种机制就是synchronized关键字,它包括两种用法:synchronized方法和synchronized块
同步方法:public synchronized void method(int args){}
synchronized方法控制对“对象”的访问,每个对象对应一把锁,每个synchronized方法都i必须获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,知道该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行。
缺陷:若将一个大的方法申明为synchronized将会影星程序运行的效率
同步块:synchronized(obj){}
obj称之为同步监视器
obj可以是任务对象,但是推荐使用贡献资源作为同步监视器
同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this,就是这个对象本身,或者是class
同步监视器的执行过程
1、第一个线程访问,锁定同步监视器,执行其中代码
2、第二个线程访问,发现同步监视器被锁定,无法访问
3、第一个线程访问完毕,解锁同步监视器
4、第二个线程访问,发现同步监视器没有锁,人后锁定访问
安全的买票只需要在buy方法前面加上synchronized关键字
//安全的买票
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket buyTicket = new BuyTicket();
new Thread(buyTicket, "张三").start();
new Thread(buyTicket, "李四").start();
new Thread(buyTicket, "黄牛").start();
}
}
class BuyTicket implements Runnable{
//票
private int ticketNums = 10;
boolean flag = true; //外部停止方式
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see Thread#run()
*/
@Override
public void run() {
//买票
while(flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//==============synchronized同步方法,锁的时this关键字==================
private synchronized void buy() throws InterruptedException {
//判断是否有票
if(ticketNums <= 0){
flag = false;
return;
}
//模拟延时
Thread.sleep(1000);
//买票
System.out.println(Thread.currentThread().getName() + "拿到" + ticketNums--);
}
}
结果:
张三拿到10
张三拿到9
张三拿到8
张三拿到7
张三拿到6
张三拿到5
张三拿到4
张三拿到3
张三拿到2
张三拿到1
Process finished with exit code 0
安全的取钱
//不安全的取钱
//两个人去银行取钱,账户
public class UnsafeBank {
public static void main(String[] args) {
//账户
Account account = new Account(100, "基金");
Drawing you = new Drawing(account, 50, "你");
Drawing girlFriend = new Drawing(account, 100, "girlFriend");
you.start();
girlFriend.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;
this.nowMoney = nowMoney;
}
//取钱
/**
* If this thread was constructed using a separate
* {@code Runnable} run object, then that
* {@code Runnable} object's {@code run} method is called;
* otherwise, this method does nothing and returns.
* <p>
* Subclasses of {@code Thread} should override this method.
*
* @see #start()
* @see #stop()
* @see #Thread(ThreadGroup, Runnable, String)
*/
@Override
public void run() {
synchronized (account){ //==================synchronized==================
//判断有没有钱
if(account.money - drawingMoney < 0){
System.out.println(Thread.currentThread().getName() + "已经没钱了");
return;
}
//sleep可以放大问题的发生性
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额=余额-取的钱
account.money = account.money - drawingMoney;
//你手里的钱
nowMoney = nowMoney+drawingMoney;
System.out.println(account.name+"的余额为:"+account.money);
//Thread.currentThread().getName() = this.getName()
System.out.println(this.getName()+"手里的钱为:"+nowMoney);
}
}
}
结果:
基金的余额为:50
你手里的钱为:50
girlFriend已经没钱了
Process finished with exit code 0
安全的集合
import java.util.ArrayList;
//线程不安全的集合
public class UnsafeList {
public static void main(String[] args) throws InterruptedException {
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
synchronized (list){//==============================
list.add(Thread.currentThread().getName());
}
}).start();
}
Thread.sleep(3000);
System.out.println(list.size());
}
}
安全的集合有一个已经写好的类叫做CopyOnWriteArrayList
这是在java.util.concurrent.CopyOnWriteArrayList中的一个类,已经帮我们处理了线程同步的问题,不需要再写Synchronized关键字了。
import java.util.concurrent.CopyOnWriteArrayList;
//测试JUC安全类型的集合
public class TestJUC {
public static void main(String[] args) throws InterruptedException {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
Thread.sleep(3000);
System.out.println(list.size());
}
}
死锁问题
//死锁:多个线程互相抱着对方需要的资源,然后形成僵持
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;
}
/**
* If this thread was constructed using a separate
* {@code Runnable} run object, then that
* {@code Runnable} object's {@code run} method is called;
* otherwise, this method does nothing and returns.
* <p>
* Subclasses of {@code Thread} should override this method.
*
* @see #start()
* @see #stop()
* @see #Thread(ThreadGroup, Runnable, String)
*/
@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.getName() + "获得口红的锁");
Thread.sleep(1000);
synchronized (mirror){
System.out.println(this.getName() + "获得镜子的锁");
}
}
}else { //获得镜子的锁
synchronized (mirror) {
System.out.println(this.getName() + "获得口红的锁");
Thread.sleep(1000);
synchronized (lipstick) {
System.out.println(this.getName() + "获得镜子的锁");
}
}
}
}
}
死锁避免的方法:
1、互斥条件:一个资源每次只能被一个进程使用
2、请求于保持条件:一个进程因请求资源二阻塞时,对已经获得的资源保持不放
3、不剥夺条件:进程已经获得的资源,再=在未使用前,不能强行剥夺
4、循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系
Lock(锁)
从JDK5.0开始,Java提供了更强的线程同步机制——通过显式定义同步锁对象实现同步,同步锁使用Lock对象充当。
java.util.concurrent.locks.lock接口是控制多个线程对共享资源进行访问的工具,锁提供了对共享资源的独占访问,每次只能由一个线程对lock对象加锁,线程开始访问共享资源之前应先获得lock对象。
ReentrantLock(可重入锁)类实现了lock,它拥有与synchronized现同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentrantLock,可以显示加锁,释放锁。
import java.util.concurrent.locks.ReentrantLock;
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 = 20;
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see Thread#run()
*/
@Override
public void run() {
//定义Lock锁
ReentrantLock lock = new ReentrantLock();
while(true){
//try {
// Thread.sleep(1000);
//} catch (InterruptedException e) {
// e.printStackTrace();
//}
try{
lock.lock();
if(ticketNums > 0){
//try {
// Thread.sleep(1000);
//} catch (InterruptedException e) {
// e.printStackTrace();
//}
System.out.println(Thread.currentThread().getName() + ticketNums--);
}else{
break;
}
}finally {
//解锁
lock.unlock();
}
}
}
}
线程协作——消费者与生产者模式
这是一个线程问题,生产者和消费者共享同一个资源,并企鹅生产者和消费者之间相互啊依赖,互为条件
-
对于生产者,没有生产产品之前,要通知消费者等待,而产生了产品之后,有需要马上同值消费者消费
-
对于消费者,在消费之后,要通知生产者已经结束消费,需要生产新的产品以供消费
-
在生产者消费问题中,仅有synchronized是不够的
synchronized可以阻止并发更新统一个共享资源,实现了同步
synchronized不能用来实现不同线程之间的消息传递(通信)
Java提供了几个方法解决线程之间的通信问题:
wait():表示线程一致等待,直到其他线程通知,与sleep不同,wait可以释放锁
wait(long timeout):指定等待的毫秒数**(1000毫秒等于1秒)**
notify():唤醒一个处于等待状态的线程
notifyAll():唤醒同一个对象上的所有调用wait()方法的线程,优先级别高的线程优先调度
注意:
以上均为Object类的方法,都只能在同步方法或者同步代码中使用,否则会出现异常illegalMontionStateException
并发写作模型“生产者/消费者模式”—>管程法
生产者:负责生产数据的模块(方法、对象、线程、进程)
消费者:负责处理数据的模块(方法、对象、线程、进程)
缓冲区:消费者不能直接使用生产者的数据,它们之间有一个缓冲区
生产者将生产的数据放入缓冲区,消费者从缓冲区拿出数据进行处理
//测试:生产者消费者模型——利用缓冲区解决:管程法
//生产者、消费者、产品、缓冲区
public class TestPC {
public static void main(String[] args) {
SynContainer container = new SynContainer();
new Product(container).start();
new Consumer(container).start();
}
}
//生产者
class Product extends Thread{
SynContainer container;
public Product(SynContainer container){
this.container = container;
}
//生产
/**
* If this thread was constructed using a separate
* {@code Runnable} run object, then that
* {@code Runnable} object's {@code run} method is called;
* otherwise, this method does nothing and returns.
* <p>
* Subclasses of {@code Thread} should override this method.
*
* @see #start()
* @see #stop()
* @see #Thread(ThreadGroup, Runnable, String)
*/
@Override
public void run() {
for (int i = 0; i < 100; i++) {
container.push(new Chicken(i));
System.out.println("生产了" + i + "只鸡");
}
}
}
class Consumer extends Thread{
SynContainer container;
public Consumer(SynContainer container){
this.container = container;
}
//消费
/**
* If this thread was constructed using a separate
* {@code Runnable} run object, then that
* {@code Runnable} object's {@code run} method is called;
* otherwise, this method does nothing and returns.
* <p>
* Subclasses of {@code Thread} should override this method.
*
* @see #start()
* @see #stop()
* @see #Thread(ThreadGroup, Runnable, String)
*/
@Override
public void run() {
for (int i = 0; i < 100; 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:信号灯法
//测试生产者消费者模式问题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 {
private TV tv;
public Player(TV tv){
this.tv = tv;
}
/**
* If this thread was constructed using a separate
* {@code Runnable} run object, then that
* {@code Runnable} object's {@code run} method is called;
* otherwise, this method does nothing and returns.
* <p>
* Subclasses of {@code Thread} should override this method.
*
* @see #start()
* @see #stop()
* @see #Thread(ThreadGroup, Runnable, String)
*/
@Override
public void run() {
for (int i = 0; i < 20; 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;
}
/**
* If this thread was constructed using a separate
* {@code Runnable} run object, then that
* {@code Runnable} object's {@code run} method is called;
* otherwise, this method does nothing and returns.
* <p>
* Subclasses of {@code Thread} should override this method.
*
* @see #start()
* @see #stop()
* @see #Thread(ThreadGroup, Runnable, String)
*/
@Override
public void run() {
for (int i = 0; i < 20; i++) {
tv.watch();
}
}
}
//产品-->节目
class TV{
//演员表演,观众等待 T
//观众观看,演员等待 F
String voice; //表演的节目
boolean flag = true;
//表演
public synchronized void play(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;
}
}
线程池
背景: 经常创建和销毁,使用大量的资源,比如并发情况下的线程,对性能的映像很大
思路: 提前创建好多个线程,放入线程池中,使用的时候直接获取,使用完放回池中,可以避免频繁创建和销毁,实现重复利用。
好处:
提高响应速度
降低资源损耗
便于线程管理
corePoolSize:核心池的大小
maximumPoolSize:最大线程数
keepAliveTime:线程没有任务时最多保持多长时间后会终止
JDK5.0开始提供了相关线程池的API:ExecutorService和Executors
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
//测试线程池
public class TestPool {
public static void main(String[] args) {
//1、创建服务,创建线程池
//newFixedThreadPool 参数为:线程池的大小
ExecutorService service = Executors.newFixedThreadPool(10);
//2、执行
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
//3、关闭连接
service.shutdown();
}
}
class MyThread implements Runnable{
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see Thread#run()
*/
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "-->" + i);
}
}
}