多线程
基本定义
线程和进程一样,都是实现并发的一个基本单位,线程是比进程更小的执行单位,线程是在进程的基础之上进行的进一步划分。多线程是实现并发机制的一种有效的手段,0所谓多线程是指一个线程在执行的过程当中可产生多个线程,这些线程可以同时存在,同属运行。一个进程可能包含多个同时执行的线程。
继承Thread类
基本格式
package com;
public class TestThread1 implements Runnable{
@Override
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();
Thread thread=new Thread(testThread1);
thread.start();
// testThread1.start();
for (int i = 0; i < 20; i++) {
System.out.println("我在学线程"+i);
}
}
}
实例之在网络上下载图片
package com;
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() {
WebDownload webDownload=new WebDownload();
webDownload.downloader(url,name);
System.out.println("下载了文件名为:"+name);
}
public static void main(String[] args) {
TestThread2 t1=new TestThread2("https://dss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1112559807,641369579&fm=26&gp=0.jpg","疯狂的兔子.jpg");
TestThread2 t2=new TestThread2("https://dss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1371504364,3574377056&fm=26&gp=0.jpg","可爱的煎饼.jpg");
TestThread2 t3=new TestThread2("https://dss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3260566216,3796351013&fm=26&gp=0.jpg","兔兔.jpg");
t1.start();
t2.start();
t3.start();
}
}
class WebDownload{
//下载器
//下载方法
public void downloader(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("从网络下载图片出现失误");
}
}
}
继承Runnable类
package com;
//多个线程同时操作同一个对象
//买火车票的例子
//数据紊乱,数据的并发问题
public class TestThread4 implements Runnable{
private int ticketNums=10;//权限控制
@Override
public void run() {
while (true){
if(ticketNums<=0){
break;
}
try {
Thread.sleep(200);//模拟延时
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"拿到了"+ticketNums--+"票");
}
}
public static void main(String[] args) {
TestThread4 ticket=new TestThread4();
new Thread(ticket,"小明").start();
new Thread(ticket,"老师").start();
new Thread(ticket,"黄牛党").start();
}
}
实现比较Thread和Runnabe的区别:
TestThread1 testThread1=new TestThread1();
testThread1.start();
TestThread4 ticket=new TestThread4();
new Thread(ticket,"小明").start();
等同于
TestThread4 testThread4=new TestThread4();
Thread thread=new Thread(testThread4);
thread.start();
Thread和Runnable的区别
- 多线程的两种实现方法都需要一个线程的主类,而这个类可以实现Runnable接口或继承Thread类,不管使用何种方式都必须在子类中覆写run()方法,此方法为线程的主方法
- Thread类是Runnable接口的子类,而且使用Runnable接口可以避免单继承局限,并且可以更加方便的实现数据共享的概念
龟兔赛跑
package com;
//模拟龟兔赛跑-
public class TestThread5 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 stepts){
if(winner!=null){
System.out.println("已经存在顺利者了");
return true;
}{
if(stepts>=100){
winner=Thread.currentThread().getName();
System.out.println("Winner is"+winner);
return true;
}
}
return false;
}
public static void main(String[] args) {
TestThread5 race=new TestThread5();
new Thread(race,"兔子").start();
new Thread(race,"乌龟").start();
}
}
Callable
静态代理模式
package com;
//静态代理模式总结:
//真实对象和代理对象都要实现同一个接口
//代理对象要代理真实角色
//好处:代理对象可以做很多真实对象做不了的事情
//真实对象专注袭击的事情
public class TestThread6 {
public static void main(String[] args) {
you you=new you();
new Thread(()->System.out.println("我爱你")).start();
new WeddingCompany(new you()).HappyMarry();
// WeddingCompany weddingCompany = new WeddingCompany(new you());
// weddingCompany.HappyMarry();
}
}
interface Marry {
//久旱逢甘露,他乡遇故知,洞房花烛夜,金榜题名时
void HappyMarry();
}
class you implements Marry {
//真实角色
@Override
public void HappyMarry() {
System.out.println("老师要结婚了,超开心");
}
}
//代理角色--
class WeddingCompany implements Marry {
private Marry target;
public WeddingCompany(Marry target) {
this.target = target;
}
@Override
public void HappyMarry() {
brfore();
this.target.HappyMarry();
after();
}
private void brfore() {
System.out.println("结婚之前,布置现场");
}
private void after() {
System.out.println("结婚之后,收尾款");
}
}
Lamda表达式
- 希腊表中排序第十一的字母,
- 避免匿名内部类定义过多
- 其实质属于函数式编程的概念
new Thread(()->System.out.println(“我爱你”)).start();
函数式接口
- 任何接口,如果只包含唯一一个抽象方法,那么他就是一个函数式的接口
- 用Lamda来创建接口
package com;
public class TestLambda1 {
//静态内部类
static class Like2 implements ILike{
@Override
public void lambda() {
System.out.println("I like lambda2");
}
}
public static void main(String[] args) {
ILike like=new Like();//接口调用一个实现类
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() {
@Override
public void lambda() {
System.out.println("I like lambda4");
}
};
like.lambda();
like=()->{ System.out.println("I like lambda5");
};
like.lambda();
}
//6.用lambda简化
}
//1.定义一个函数式接口
interface ILike{
void lambda();
}
//2.实现类
class Like implements ILike{
@Override
public void lambda() {
System.out.println("I like lambda");
}
}
package com;
public class TestLambda2 {
// //静态内部类
// static class Love implements Ilove{
//
// @Override
// public void love(int a) {
// System.out.println("I Love you"+a);
// }
// }
public static void main(String[] args) {
// //局部内部类
// class Love implements Ilove{
//
// @Override
// public void love(int a) {
// System.out.println("I Love you"+a);
// }
// }
//
// Ilove Love=new Love();
// Love.love(2);
// Ilove Love=new Ilove() {
// @Override
// public void love(int a) {
// System.out.println("I Love you"+a);
// }
// };
// Love.love(2);
Ilove Love=(int 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 you1");
// }
//}
package com;
public class TestLambda2 {
// //静态内部类
// static class Love implements Ilove{
//
// @Override
// public void love(int a) {
// System.out.println("I Love you"+a);
// }
// }
public static void main(String[] args) {
// //局部内部类
// class Love implements Ilove{
//
// @Override
// public void love(int a) {
// System.out.println("I Love you"+a);
// }
// }
//
// Ilove Love=new Love();
// Love.love(2);
// Ilove Love=new Ilove() {
// @Override
// public void love(int a) {
// System.out.println("I Love you"+a);
// }
// };
// Love.love(2);
//1.
// Ilove Love=(int a)->{ System.out.println("I Love you"+a);};
// Love.love(520);
//2.
// Ilove Love=null;
// Love= a->{ System.out.println("I Love you"+a);};
// Love.love(520);
//3.
//总结:lambda表达式只能有遗憾代码的情况下才能简化成为一行若果有多行,那么利用代码块进行包括
//2.必须前提是函数式接口--接口只有一个方法
//多个参数也可以去掉参数类型,要去掉就都去掉,必须加上括号
// 能去掉花括号的原因在于代码只有一行
Ilove Love=null;
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 you1");
// }
//}
t步骤:定义一个函数接口–>实现类–>静态内部类–>静态内部类放在Main方法里面变成局部内部类–>不想起名,变成匿名内部类–>再简化变成lambda(jdk新增)
线程状态
- 创建状态
- 就绪状态
- 运行状态
- 阻塞状态
- 死亡状态
多线程停止__stop
package state;
//测试stop
//1.建议线程正常停止,利用次数,不建议死循环
//2.建议使用标识位
//不要使用stop或者destory等过时方法
public class Teststop implements Runnable {
//1.设置一个标识位
private boolean flag=true;
@Override
public void run() {
int i=0;
while (flag){
System.out.println("rub...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 < 1000; i++) {
System.out.println("main"+i);
if(i==900){
teststop.stop();
System.out.println("线程该停止了");
}
}
}
}
线程休眠__sleep
package state;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestSleepTwo {
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();
}
}
}
}
线程礼让__yield
package state;
//测试礼让线程:礼让不一定成功,看cpu心情
public class TestYiled {
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
package state;
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();
// new Thread(testjoin).start();
for (int i = 0; i < 1000; i++) {
if(i==200){
thread.join();//插队
}
System.out.println("main"+i);
}
}
}
线程观测状态
参考一下之前的ppt
Thread.state
- new
- runnable
- blocked
- waitting
- timed_waitting
- terminated
package state;
//观察线程的状态
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(200);
} 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);//RUN
while (state!= Thread.State.TERMINATED){
Thread.sleep(100);
state=thread.getState();//更新状态
System.out.println(state);
}
thread.start();//死亡后的线程不可以再运行
}
}
线程优先级__priority
先设置优先级,再启动
优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了,这都是看cpu的调度
getPriority().setPriority(int xxx)
- 线程优先级用数字表示:1-10
package state;
import java.util.logging.SocketHandler;
public class TestPriority {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
MyPririty myPririty=new MyPririty();
Thread t1=new Thread(myPririty);
Thread t2=new Thread(myPririty);
Thread t3=new Thread(myPririty);
Thread t4=new Thread(myPririty);
Thread t5=new Thread(myPririty);
t1.start();
t2.start();
t3.start();
t4.start();
t4.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(2);
}
}
class MyPririty implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
}
}
守护(daemon)线程
- 线程分为用户线程和守护线程
- 虚拟机必须确保用户线程执行完毕
- 虚拟机不应等待守护线程执行完毕
package state;
//测试守护线程
public class TestDemo {
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(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("你一生都开心的活着"+i);
}
System.out.println("-=====goodbye!world");
}
}
线程同步
*多个线程操作同一个资源
并发:同一个对象被多个线程操作
Eg:上万人同时抢1000张票 、 两个银行同时取钱
处理多线程问题的时候,多个线程访问同一个对象,某些线程还想修改这个对象,此时我们就需要线程同步,线程同步实际上是等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面的线程使用完毕
形成条件:队列+锁(synchronized)
三大不安全案例
package state;
//不安全的买票
//线程不安全,有负数(当票数海域1的时候,他们呢以为自己都可以)
//每个线程在自己的工作内存交互,内存控制不当会造成数据的不一致
public class UnnSafeBuyTicket {
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{
//票
private int ticketNums=10;
boolean flag=true;//外部停止方式
@Override
public void run() {
//买票
while (flag){
buy();
}
}
private void buy(){
if(ticketNums<=0){
return;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}
package state;
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 int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = 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(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
account.money=account.money-drawingMoney;
nowMoney=nowMoney+drawingMoney;
System.out.println("余额为"+account.money);
System.out.println(this.getName()+"手里的钱"+nowMoney);
}
}
package state;
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(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
同步方法
- synchronized关键字的两种用法:synchronized 和 synchronized 块
- synchronized方法控制对"对象"的访问,每个对象对于一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能进行,否则我线程堵塞
public synchronized void method(int args){}
After:
package state;
//不安全的买票
//线程不安全,有负数(当票数海域1的时候,他们呢以为自己都可以)
//每个线程在自己的工作内存交互,内存控制不当会造成数据的不一致
public class UnnSafeBuyTicket {
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{
//票
private int ticketNums=10;
boolean flag=true;//外部停止方式
@Override
public void run() {
//买票
while (flag){
buy();
}
}
//同步方法
private synchronized void buy(){
if(ticketNums<=0){
return;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}
synchoronized(obj){} 锁的量是变化的量–增删改
package state;
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 int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = 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(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
account.money = account.money - drawingMoney;
nowMoney = nowMoney + drawingMoney;
System.out.println("余额为" + account.money);
System.out.println(this.getName() + "手里的钱" + nowMoney);
}
}
}
CopyOnWriteArrayList
package state;
import java.util.concurrent.CopyOnWriteArrayList;
public class TestJUC {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list=new CopyOnWriteArrayList<String>();
for (int i = 0; i < 1000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
死锁
多个线程占有一些共享资源,并且互相等待其他线程占有的资源才能运行,而导致两个或者多个线程在等待对方释放资源,都停止执行的情形。某一个同步块同时拥有“两个以上对象的锁”
产生死锁的四个必要条件:
- 互斥条件:一个资源每次只能被一个进程使用
- 请求与保持条件:一个进程因请求资源而阻塞的时候,对已获得的资源保持不放
- 不剥夺条件:进程已获得的资源,在未使用完之前,不能强行剥夺
- 循环等待条件:若干进程之间形成一种头尾相接的循环等待资源
package state;
//死锁:多个线程互相抱着对方的资源,然后形成僵持
public class DeadLock {
public static void main(String[] args) {
Makup g1=new Makup(0,"灰姑娘");
Makup g2=new Makup(1,"白雪公主");
g1.start();
g2.start();
}
}
//口红
class Lipstick{
}
//镜子
class mirror{
}
//化妆
class Makup extends Thread {
Lipstick lipstick = new Lipstick();
mirror mirror = new mirror();
int choice;//选择
String girlName;//女生名字
Makup(int choice, String girlName) {
this.choice = choice;
this.girlName = girlName;
}
@Override
public void run() {
//化妆
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//化妆需要拿到对方的资源
public void makeup() throws InterruptedException {
if (choice == 0) {
synchronized (lipstick) {//获得口红的锁
System.out.println(this.girlName + "获得口红的锁");
Thread.sleep(200);
}
synchronized (mirror) {
System.out.println(this.girlName + "获得镜子的锁");
}
}else {
synchronized (mirror) {//获得口红的锁
System.out.println(this.girlName + "获得镜子的锁");
Thread.sleep(200);
}
synchronized (lipstick) {
System.out.println(this.girlName + "获得口红的锁");
}
}
}
}
Lock
package state;
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 ticketNum=10;
//定义Lock锁
private final ReentrantLock lock=new ReentrantLock();
@Override
public void run() {
while (true){
try {
lock.lock();//加锁
if(ticketNum>0){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNum--);
}else {
break;
}
}finally {
//解锁
lock.unlock();
}
}
}
}
synchronized和Lock的区别
- Lock是显式锁(手动开启和关闭锁,别忘记关闭锁),synchronized是隐式锁,出了作用域自动释放
- Lock只有代码块锁,synchronized有代码块锁和方法 锁
- 使用Lock锁,JVM将花费较少的时间来调度线程,性能更好,并且具有更好的扩展性(提供更多的子类)
- 优先使用顺序
- Lock>同步代码块(已经进入了方法体,分配了相应的资源)>同步方法(在方法体之外)
class A{
private final ReentrantLock lock=new ReentrantLock();
public void m(){
lock.lock();
try{
}
finally{
lock.unlock();
}
}
}