多线程详解
线程简介
Process与Thread
- 说起进程,就不得不说下程序。程序是指令和数据的有序集合,其本身没有任何运行的含义,是一个静态的概念。
- 而进程则是执行程序的一次执行过程,它是一个动态的概念。是系统资源分配的单位。
- 通常在一个进程中可以包含若干个线程,当然一个进程中至少有一个线程,不然没有存在的意义。线程是CPU调度和执行的的单位。
注意:很多多线程是模拟出来的,真正的多线程是指有多个cpu,即多核,如服务器。如果是模拟出来的多线程,即在一个cpu的情况下,在同一个时间点,cpu只能执行一个代码,因为切换的很快,所以就有同时执行的错局。
概念
- 线程就是独立的执行路径;
- 在程序运行时,即使没有自己创建线程,后台也会有多个线程,如主线程,gc线程;main()称之为主线程,为系统的入口,用于执行整个程序;
- 在一个进程中,如果开辟了多个线程,线程的运行由调度器安排调度,调度器是与操作系统紧密相关的,先后顺序是不能人为的干预的。
- 对同一份资源操作时,会存在资源抢夺的问题,需要加入并发控制:
- 线程会带来额外的开销,如cpu调度时间,并发控制开销。
- 每个线程在自己的工作内存交互/内存控制不当会造成数据不一致
线程实现
三种创建方式
Thread calss ------->继承Thread(重点)
继承Thread类
子类继承Thread类具备多线程能力?
启动线程:子类对象. start/
不建议使用:避免OOP单继承局限性
//创建线程方式一:继承Thread类,重写run()方法,调用start开启线程
public class TestThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("我在看代码----"+i);
}
}
//mian线程
public static void main(String[] args) {
//创建一个线程对象
TestThread testThread = new TestThread();
//调用start()方法开启线程
testThread.start();//同时执行
//testThread.run();//先执行run,后执行main
for (int i = 0; i < 200; i++) {
System.out.println("我在学习线程"+i);
}
}
}
Runnable接口-------> 实现Runnable接口(重点)
实现Runnable接口
实现接口Runnable具有多线程能力
启动线程:传入目标对象+Thread对象. start/)
推荐使用:避免单继承局限性,灵活方便,方便同一个对象被多个线程使用
//创建线程方式二:实现runnable接口,重写run()方法,执行线程需要丢入runnable接口实现类,调用start开启线程
public class TestThread implements Runnable{
@Override
public void run() {
for (int i = 0; i < 20; i++) {
System.out.println("我在看代码----" + i);
}
}
public static void main(String[] args) {
//创建runnable接口的实现类对象
TestThread testThread = new TestThread();
//创建线程对象,通过线程对象来开启我们的线程,代理
// Thread thread = new Thread(testThread);
// thread.start();
new Thread(testThread).start();
for (int i = 0; i < 500; i++) {
System.out.println("我在学习多线程--"+i);
}
}
}
//模拟龟兔赛跑
public class Race implements Runnable{
//胜利者
private static String winner;
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
//模拟兔子休息
if (Thread.currentThread().getName().equals("兔子") && i%10==0){
try{
Thread.sleep(200);
} 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>=100){
winner=Thread.currentThread().getName();
System.out.println("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方法,需要抛出异常
静态代理
//静态代理模式总结
//真实对象和代理对象都要实现同一个接口
//代理对象要代理真实角色
//好处:
//代理对象可以做很多真实对象做不了事情
//真实对象专注做自己的事情
public class StacticProxy {
public static void main(String[] args) {
new Thread(()-> System.out.println("我爱你")).start();
new WeddingCompany(new You()).HappMarry();
}
}
interface Marry{
void HappMarry();
}
//真实角色,你去结婚
class You implements Marry{
@Override
public void HappMarry() {
System.out.println("你要结婚了,开心");
}
}
//代理角色,帮助你结婚
class WeddingCompany implements Marry{
private Marry target;
public WeddingCompany(Marry target){
this.target = target;
}
@Override
public void HappMarry() {
after();
this.target.HappMarry();//真实对象
before();
}
private void after() {
System.out.println("结婚之前布置现场");
}
private void before() {
System.out.println("结婚之后,收尾款");
}
}
线程状态
线程休眠
//模拟倒计时
public class Demo {
public static void main(String[] args) {
try {
tenDown();
} 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;
}
}
}
}
每个对象都有一个锁,sleep不会释放锁。
线程礼让
- 礼让线程,让当前正在执行的线程暂停,但不阻塞
- 将线程从运行状态转为就绪状态
- 让cpu重新调度,礼让不一定成功!看cpu心情。
//模拟礼让
public class Demo {
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合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞。
//模拟Jion方法
public class Demo 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 {
Demo demo = new Demo();
//启动线程
Thread thread = new Thread(demo);
thread.start();
//主线程
for (int i = 0; i < 1000; i++) {
if (i==200){
thread.join();//插队
}
System.out.println("主线程"+i);
}
}
}
观测线程状态
public class Demo {
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);
while(state !=Thread.State.TERMINATED){//只要线程不终止,就一直输出状态
Thread.sleep(1000);
state = thread.getState();//跟新线程状态
System.out.println(state);//输出状态
}
}
}
线程优先级
-
Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行。
-
线程的优先级用数字表示,范围从1~10
- Thread.MIN_PRIORITY = 1;
- Thread.MAX_PRIORITY = 10;
- Thread.NORM_PRIORITY = 5; ----->默认值是5
-
使用以下方式获取优先级
getPriority().setPriority(int xxx)
//测试线程的优先级
public class Demo {
public static void main(String[] args) {
//主线程默认优先级
System.out.println(Thread.currentThread().getName()+"主线程--->"+Thread.currentThread().getPriority());
MyPriority myPriority = new MyPriority();
Thread thread = new Thread(myPriority);
Thread thread1 = new Thread(myPriority);
Thread thread2 = new Thread(myPriority);
Thread thread3 = new Thread(myPriority);
Thread thread4 = new Thread(myPriority);
Thread thread5 = new Thread(myPriority);
//设置优先级,再启动
thread.start();
thread1.start();
thread2.setPriority(1);
thread2.start();
thread3.setPriority(4);
thread3.start();
thread4.setPriority(10);
thread4.start();
thread5.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"--->"+Thread.currentThread().getPriority());
}
}
注意:优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了,这都是看CPU的调度。
守护(daemon)线程
- 线程分为用户线程和守护线程
- 虚拟机必须确保用户线程执行完毕
- 虚拟机不用等待守护线程执行完毕
- 如:后台记录操作日志,监控内存,垃圾回收等等
//测试守护线程
public class Demo {
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 < 30000; i++) {
System.out.println("一直开心的活着");
}
System.out.println("====goodbye!word!======");
}
}
线程同步
并发
- 同一个对象被多个线程同时操作
- 处理多线程问题时,多个线程访问同一个对象,并且某些线程还想修改这个对象,这时候我们就需要线程同步。线程同步其实就是一种等待机制,多个需要同时访问此多想的线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一个线程再使用。
队列和锁
- 由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制 synchronized ,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可.存在以下问题:
- 一个线程持有锁会导致其他所有需要此锁的线程挂起;
- 在多线程竞争下,加锁,释放锁会导致比较多的上下文切换和调度延时,引起性能问题;
- 如果一个优先级高的线程等待一个优先级低的线程释放锁会导致优先级倒置,引起性能问题.
三大不安全案例
//不安全的买票
public class Demo {
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;
@Override
public void run() {
//买票
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void buy() throws InterruptedException {
//判断是否有票
if (ticketNums<=0){
return;
}
//模拟延时
Thread.sleep(1000);
//买票
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 you1 = new Drawing(account, 100, "他**");
you.start();
you1.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);
// Thread.currentThread().getName() = this.getName();
System.out.println(this.getName()+"手里的钱:"+nowMoney);
}
}
//线程不安全集合
public class UnsafeList {
public static void main(String[] args) {
ArrayList<String> strings = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
strings.add(Thread.currentThread().getName());
}).start();
}
System.out.println(strings.size());
}
}
同步方法
- 由于我们可以通过private关键字来保证数据对象只能被方法访问,所以我们只需要针对方法提出一套机制,这套机制就是 synchronized 关键字,它包括两种用法: synchronized 方法和 synchronized 块.
同步方法:public synchronized void method(int args){}
- synchronized 方法控制对“对象”的访问,每个对象对应一把锁,每个 synchronized 方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得得这个锁,继续执行
缺陷;若将一个大的方法申明为 synchronized 将会影响效率
public class Demo {
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;
@Override
public void run() {
//买票
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//synchronized 同步方法,锁的是this
private synchronized void buy() throws InterruptedException {
//判断是否有票
if (ticketNums<=0){
return;
}
//模拟延时
Thread.sleep(1000);
//买票
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}
- 锁的对象就是变化的量,需要的增删改的对象
//不安全的取钱
//两个人去银行取钱,账户
public class UnsafeBank {
public static void main(String[] args) {
//账户
Account account = new Account(1000, "基金");
Drawing you = new Drawing(account, 50, "你");
Drawing you1 = new Drawing(account, 100, "他**");
you.start();
you1.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;
}
//取钱
//synchronized 默认锁的是this
@Override
public void run() {
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);
// Thread.currentThread().getName() = this.getName();
System.out.println(this.getName()+"手里的钱:"+nowMoney);
}
}
}
//线程不安全集合
public class UnsafeList {
public static void main(String[] args) throws InterruptedException {
ArrayList<String> strings = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
synchronized (strings){
strings.add(Thread.currentThread().getName());
}
}).start();
}
Thread.sleep(1000);
System.out.println(strings.size());
}
}
同步块
- 同步块:synchronized(Obj){}
- Obj称之为同步监视器
- Obj可以是任何对象,但是推荐使用共享资源作为同步监视器
- 同步方法中无需指定同步监视器,因为同步方法中的同步监视器就是this,就是这个对象本身,或者是class
- 同步监视器的执行过程
- 第一个线程访问,锁定同步监视器,执行其中代码
- 第二个线程访问,发次同步监视器被锁定,无法访问
- 第一个线程访问完毕,解锁同步监视器
- 第二个线程访问,发现同步监视器没有锁,然后锁定并访问