多线程
多任务
普通方法调用和多线程
普通方法(调用run()方法)效率低
//创建线程方式一:继承Thread类,重写run()方法,调用start开启线程
//总结:注意,线程开启不一定立即执行,由cpu调度执行
public class TestThread1 extends Thread{
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 10; i++) {
System.out.println("我在看电视--"+i);
}
}
public static void main(String[] args) {
//main线程,主线程
//创建一个线程对象
TestThread1 testThread1 = new TestThread1();
//调用run()方法开启线程
testThread1.run();
for (int i = 0; i < 10; i++) {
System.out.println("我在执行main--"+i);
}
}
}
结果,如下图
多线程(调用start()方法)效率高
//创建线程方式一:继承Thread类,重写run()方法,调用start开启线程
//总结:注意,线程开启不一定立即执行,由cpu调度执行
public class TestThread1 extends Thread{
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 10; i++) {
System.out.println("我在看电视--"+i);
}
}
public static void main(String[] args) {
//main线程,主线程
//创建一个线程对象
TestThread1 testThread1 = new TestThread1();
//调用start()方法开启线程
testThread1.start();
for (int i = 0; i < 10; i++) {
System.out.println("我在执行main--"+i);
}
}
}
结果,如下图
进程与线程
核心概念
线程的创建
Thread
//创建线程方式一:继承Thread类,重写run()方法,调用start开启线程
//总结:注意,线程开启不一定立即执行,由cpu调度执行
public class TestThread1 extends Thread{
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 10; i++) {
System.out.println("我在看电视--"+i);
}
}
public static void main(String[] args) {
//main线程,主线程
//创建一个线程对象
TestThread1 testThread1 = new TestThread1();
//调用start()方法开启线程
testThread1.start();
for (int i = 0; i < 10; i++) {
System.out.println("我在执行main--"+i);
}
}
}
Runnable
//创建线程方式2:实现runnable接口,重写run方法,执行线程需要丢入runnable接口实现类,调用start方法
public class TestThread1 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("我在执行run--"+i);
}
}
public static void main(String[] args) {
//创建runnable接口的实现类对象
TestThread1 testThread1 = new TestThread1();
//创建线程对象,通过线程对象来开启我们的线程,代理
Thread thread = new Thread(testThread1);
thread.start();
for (int i = 0; i < 10; i++) {
System.out.println("我在执行main--"+i);
}
}
}
对比Thread和Runnable
初始并发问题(火车票)
//多个线程同时操作同一个对象
//买火车票的例子
//发现问题:多个线程操作同一个资源的情况下,线程不安全
public class TestThread1 implements Runnable{
//票数
private int ticketNums = 10;
@Override
public void run() {
while (true){
if (ticketNums<=0){
break;
}
System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNums--+"票");
}
}
public static void main(String[] args) {
TestThread1 testThread1 = new TestThread1();
new Thread(testThread1,"小明").start();
new Thread(testThread1,"小红").start();
new Thread(testThread1,"小乐").start();
}
}
结果,如下图
龟兔赛跑
package com.qw;
//模拟龟兔赛跑
public class TestThread1 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(1);
} 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;
}else {
if (steps>=100){
winner = Thread.currentThread().getName();
System.out.println("winner is"+winner);
return true;
}
}
return false;
}
public static void main(String[] args) {
TestThread1 testThread1 = new TestThread1();
new Thread(testThread1,"兔子").start();
new Thread(testThread1,"乌龟").start();
}
}
结果,如下图
静态代理
//静态代理模式总结:
//真实对象和代理对象都要实现同一个接口
//代理对象要代理真实角色
//好处:
//代理对象可以做很多真实对象做不了的事情
//真实对象专注做自己的事情
public class TestThread1 {
public static void main(String[] args) {
You you = new You();
new Thread( ()-> System.out.println("我爱你")).start();
new WeddingCompany(you).HappyMarry();
}
}
interface Marry{
void HappyMarry();
}
//结婚角色,You去结婚
class You implements Marry{
@Override
public void HappyMarry() {
System.out.println("结婚了,开心");
}
}
//代理角色,帮助You去结婚
class WeddingCompany implements Marry{
//代理真实目标角色
private Marry target;
public WeddingCompany(Marry target) {
this.target = target;
}
@Override
public void HappyMarry() {
before();
this.target.HappyMarry();//这就是真实对象
after();
}
private void after() {
System.out.println("结婚之后,收尾款");
}
private void before() {
System.out.println("结婚之前,布置现场");
}
}
Lamda表达式
package com.qw;
/*
推导lambda表达式
*/
public class TestThread1 {
//3.静态内部类
static class Like2 implements ILike{
@Override
public void lambda(int a) {
System.out.println("I like lambda"+a);
}
}
public static void main(String[] args) {
//实现类
ILike like = new Like();
like.lambda(0);
//静态内部类
like = new Like2();
like.lambda(1);
//4.局部内部类
class Like3 implements ILike{
@Override
public void lambda(int a) {
System.out.println("I like lambda"+a);
}
}
like = new Like3();
like.lambda(2);
//5.匿名内部类 没有类的名称,必须借助接口或者父类
like = new ILike() {
@Override
public void lambda(int a) {
System.out.println("I like lambda"+a);
}
};
like.lambda(3);
//6.用lamdba简化
like = (int a)->{
System.out.println("I like lambda"+a);
};
like.lambda(4);
//7.用lamdba简化括号,参数只能有一个才能去掉括号,否则加上括号 例如:like = (a,b)->
like = a->{
System.out.println("I like lambda"+a);
};
like.lambda(5);
//8.用lamdba简化花括号,只有一行代码才能去掉花括号简化为一行
like = a-> System.out.println("I like lambda"+a);
like.lambda(6);
}
}
//1.定义一个函数式接口(只有一个方法)
interface ILike{
void lambda(int a);
}
//2.实现类
class Like implements ILike{
@Override
public void lambda(int a) {
System.out.println("I like lambda"+a);
}
}
结果,如下图
停止线程
package com.qw;
//测试stop
//1.建议线程正常停止->利用次数,不建议死循环
//2.建议使用标志位->设置一个标志位
//3.不要使用stop或者destroy等过失或者JDK不建议使用的方法
public class Test implements Runnable{
//1.设置一个标识位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag){
System.out.println("run..Thread"+i++);
}
}
public void stop(){
this.flag = false;
}
public static void main(String[] args) {
Test test = new Test();
new Thread(test).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main"+i);
if(i==900){
test.stop();
System.out.println("线程该停止了");
}
}
}
}
结果,如下图
线程休眠
//秒钟倒计时
public class Test {
public static void tenDown() throws InterruptedException {
int num = 10;
while (true){
Thread.sleep(1000);
System.out.println(num);
num--;
if (num==0){
break;
}
}
}
public static void main(String[] args) {
try {
tenDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//打印系统时间
public static void main(String[] args) throws InterruptedException {
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();
}
}
}
线程礼让
//测试礼让线程
//礼让不一定成功,看cpu的调用
public class Test {
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
线程状态观测
//观察测试线程状态
public class Test {
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);//Run
while (state != Thread.State.TERMINATED){//只要线程不终止,就一直输出状态
Thread.sleep(100);
state = thread.getState();
System.out.println(state);
}
}
}
结果,如下图
线程优先级
//线程的优先级
public class Test {
public static void main(String[] args) throws InterruptedException {
//主线程默认优先级
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.setPriority(1);
t1.start();
t2.setPriority(5);
t2.start();
t3.setPriority(2);
t3.start();
t4.setPriority(Thread.MAX_PRIORITY);
t4.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
}
}
结果,如下图
不一定优先级越高就先执行,只是先执行概率更大
守护线程
package com.qw;
//测试守护线程
public class Test {
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();//You 启动线程
}
}
//上帝
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 < 33356; i++) {
System.out.println("活着好开心");
}
System.out.println("goodbye,world");
}
}
等到用户线程停止了,守护线程会自动停止
线程同步
三大不安全案例
1.不安全的买票
//不安全的买票
public class Test {
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 ticketNum = 10;
boolean flag = true;
@Override
public void run() {
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void buy() throws InterruptedException {
//判断是否有票
if (ticketNum<=0){
flag = false;
return;
}
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNum--);
}
}
结果,如下图
2.不安全的取钱
package com.qw;
//不安全的取钱
//两个人去银行取钱,账户
public class Test {
public static void main(String[] args) {
//账户
Account account = new Account(100,"基金");
Drawing you = new Drawing(account,50,"你");
Drawing he = new Drawing(account,100,"he");
you.start();
he.start();
}
}
//账户
class Account{
String name;//卡名
int money;//余额
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;
}
//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);
System.out.println(this.getName()+"手里的钱为:"+nowMoney);
}
}
结果,如下图
3.线程不安全的集合
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) throws InterruptedException {
List<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());
}
}
结果,如下图
同步方法
1.安全的买票
package com.qw;
//不安全的买票
public class Test {
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 ticketNum = 10;
boolean flag = true;
@Override
public void run() {
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//synchronized 同步方法,锁的是this
public synchronized void buy() throws InterruptedException {
//判断是否有票
if (ticketNum<=0){
flag = false;
return;
}
//模拟延时
Thread.sleep(100);
//买票
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNum--);
}
}
结果,如下图
2.安全的取钱
package com.qw;
//不安全的取钱
//两个人去银行取钱,账户
public class Test {
public static void main(String[] args) {
//账户
Account account = new Account(1000,"基金");
Drawing you = new Drawing(account,50,"你");
Drawing he = new Drawing(account,100,"he");
you.start();
he.start();
}
}
//账户
class Account{
String name;//卡名
int money;//余额
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;
}
//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);
System.out.println(this.getName()+"手里的钱为:"+nowMoney);
}
}
}
结果,如下图
3.线程安全的集合
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) throws InterruptedException {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
synchronized (list){
list.add(Thread.currentThread().getName());
}
}).start();
}
Thread.sleep(2000);
System.out.println(list.size());
}
}
结果,如下图
死锁
//死锁:多个线程互相抱着对方需要的资源,然后形成僵持
//此程序避免了死锁
public class Test {
public static void main(String[] args) throws InterruptedException {
Makeup g1 = new Makeup(0,"灰姑娘");
Makeup g2 = new Makeup(1,"白雪公主");
g1.start();
g2.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;
}
@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.girlName+"获得口红的锁");
Thread.sleep(1000);
}
synchronized (mirror){
System.out.println(this.girlName+"获得镜子的锁");
}
}else {
synchronized (mirror){
System.out.println(this.girlName+"获得镜子的锁");
Thread.sleep(1000);
}
synchronized (lipstick){
System.out.println(this.girlName+"获得口红的锁");
}
}
}
}
结果,如下图