? 注意:很多多线程是模拟出来的,真正的多线程是指有多个cpu,即多核,如服务器。如果是模拟出来的多线程,即在一个cpu的情况下,在同一个时间点,cpu只能执行一个代码,因为切换的很快,所以就有同时执行的错觉。
本章核心概念:
三种创建方式:
1、继承Thread类(重点)
2、实现Runnable接口(重点)
3、实现Callable接口(了解)
?
public class TestThread1 extends Thread{
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("r"+i);
}
}
public static void main(String[] args) {
//main线程,主线程
//注意:线程开启不一定立即执行,由cpu调度执行
//创建一个线程对象,调用start()方法开启线程
TestThread1 testThread1 = new TestThread1();
testThread1.start();
for (int i = 0; i < 20; i++) {
System.out.println("m"+i);
}
}
}
//实现Runnable接口,重写run()方法,执行线程需要丢入Runnable接口实现类
public class TestThread2 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 200; i++) {
System.out.println("r"+i);
}
}
public static void main(String[] args) {
//创建Runnable接口的实现类对象
TestThread2 testThread2 = new TestThread2();
//创建线程对象,通过线程对象来开启我们的线程,代理
Thread thread = new Thread(testThread2);
thread.start();
for (int i = 0; i < 1000; i++) {
System.out.println("m"+i);
}
}
}
前两种方法的区别:
抢火车票
public class TestThread3 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) {
TestThread3 ticket = new TestThread3();
new Thread(ticket,"小明").start();
new Thread(ticket,"老师").start();
new Thread(ticket,"黄牛").start();
}
}
龟兔赛跑
package Multithreading;
//模拟龟兔赛跑
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(10);
} 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();
}
}
λ希腊字母表中排序第十一位的字母
避免匿名内部类定义过多
其实质属于函数式编程的概念
函数式接口 Functional Interface:
package Multithreading;
public class TestLambda1 {
//3.静态内部类
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();
//6.Lambda表达式
like = () -> {
System.out.println("I like lambda5");
};
like.lambda();
}
}
//1.定义一个函数式接口
interface ILike{
void lambda();
}
//2.实现类
class Like implements ILike{
@Override
public void lambda() {
System.out.println("I like lambda1");
}
}
package Multithreading;
public class TestLambda2 {
public static void main(String[] args) {
//Lambda简化
ILove love = (int a)->{
System.out.println("I love you "+a);
};
//简化1.参数类型
love = (a)->{
System.out.println("I love you "+a);
};
//简化2.简化括号
love = a->{
System.out.println("I love you "+a);
};
//简化3.去掉花括号(只有一行代码的情况下才能使用)
love = a-> System.out.println("I love you "+a);
love.love(1314);
}
}
//函数式接口
interface ILove{
void love(int a);
}
package Multithreading;
//静态代理模式总结:
//真实对象和代理对象都要实现同一个接口
//代理对象要代理真实角色
public class StaticProxy {
public static void main(String[] args) {
new Thread(()-> System.out.println("I love you")).start();
new WeddingCompany(new You()).HappyMarry();
}
}
interface Marry{
void HappyMarry();
}
class You implements Marry{
@Override
public void HappyMarry() {
System.out.println("happy!");
}
}
//代理
class WeddingCompany implements Marry{
private Marry targe;
public WeddingCompany(Marry targe){
this.targe = targe;
}
@Override
public void HappyMarry() {
before();
this.targe.HappyMarry();//真实对象
after();
}
private void before(){
System.out.println("结婚前,布置现场");
}
private void after(){
System.out.println("结婚后,收尾款");
}
}
package Multithreading;
//测试stop
//1.建议线程正常停止-->利用次数,不建议死循环
//2.建议使用标志位-->设置一个标志位
//3.不要使用stop或destroy等过时或jdk不建议使用的方法
public class TestStop implements Runnable{
//1.设置一个标志位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag){
System.out.println("run...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){
//调用stop方法切换标志位使线程停止
testStop.stop();
System.out.println("线程停止");
}
}
}
}
package Multithreading;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestSleep2 {
public static void main(String[] args) {
//打印当前时间
Date date = new Date(System.currentTimeMillis());
while (true){
try {
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(date));
date = new Date(System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//模拟倒计时
public static void count() throws InterruptedException {
int num = 10;
while (true){
Thread.sleep(1000);
System.out.println(num--);
if (num<=0){
break;
}
}
}
}
package Multithreading;
public class TestYield {
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()+"线程停止执行");
}
}
待此线程执行完毕后,再执行其他线程,其他线程阻塞
可想象成插队
package Multithreading;
public class TestJoin implements Runnable {
@Override
public void run() {
for (int i = 0; i < 500; 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();
//主线程
for (int i = 0; i < 1000; i++) {
if (i==200){
thread.join();//插队
}
System.out.println("main"+i);
}
}
}
package Multithreading;
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(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);//Runnable
while (state != Thread.State.TERMINATED){//只要线程不终止,就一直输出状态
Thread.sleep(100);
state = thread.getState();
System.out.println(state);
}
}
}
Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行
package Multithreading;
public class TestPriority {
public static void main(String[] args) {
//主线程默认优先级
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
MyPriority myPriority = new 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 thread6 = new Thread(myPriority);
//先设置优先级,再启动
thread1.start();
thread2.setPriority(1);
thread2.start();
thread3.setPriority(4);
thread3.start();
thread4.setPriority(Thread.MAX_PRIORITY);//10
thread4.start();
thread5.setPriority(-1);
thread5.start();
thread6.setPriority(11);
thread6.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
}
}
? 优先级低只是意味着获得调度的概率低,主要看cpu的调度
package Multithreading;
public class TestDaemon {
public static void main(String[] args) {
God god = new God();
People people = new People();
Thread thread = new Thread(god);
thread.setDaemon(true);//默认是false表示用户线程,正常的线程都是用户线程
thread.start();//上帝守护线程启动
new Thread(people).start();//用户线程启动
}
}
class God implements Runnable{
@Override
public void run() {
while (true){
System.out.println("God bless you");
}
}
}
class People implements Runnable{
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("活着");
}
System.out.println("hello World");
}
}
并发:同一个对象被多个线程同时操作
线程同步其实是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一个线程再使用
线程同步形成条件:队列+锁??
package Multithreading;
//可能为负数,线程不安全
public class UnsafeBuyTicket{
public static void main(String[] args) {
BuyTicket station = new BuyTicket();
new Thread(station,"cat").start();
new Thread(station,"dog").start();
new Thread(station,"pig").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) {
flag = false;
return;
}
//模拟延时
Thread.sleep(100);
//买票
System.out.println(Thread.currentThread().getName() + "购买了第" + ticketNums-- + "张票");
}
}
package Multithreading;
public class UnsafeBank {
public static void main(String[] args) {
Account account = new Account(100,"零钱");
Drawing you = new Drawing(account,50,"你");
Drawing she = new Drawing(account,100,"她");
you.start();
she.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(100);
} 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);
}
}
package Multithreading;
import java.util.ArrayList;
import java.util.List;
public class UnsafeList {
public static void main(String[] args) throws InterruptedException {
List<String> list = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
Thread.sleep(100);
System.out.println(list.size());
}
}
同步方法
方法里面需要修改的内容才需要锁,锁的太多会浪费资源
同步块
买票
package Multithreading;
//可能为负数,线程不安全
public class UnsafeBuyTicket{
public static void main(String[] args) {
BuyTicket station = new BuyTicket();
new Thread(station,"cat").start();
new Thread(station,"dog").start();
new Thread(station,"pig").start();
}
}
class BuyTicket implements Runnable {
//票
private int ticketNums = 10;
boolean flag = true;
@Override
public void run() {
//买票
while (flag) {
try {
//模拟延时
Thread.sleep(100);
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//同步方法
private synchronized void buy() throws InterruptedException {
//判断是否有票
if (ticketNums <= 0) {
flag = false;
return;
}
//买票
System.out.println(Thread.currentThread().getName() + "购买了第" + ticketNums-- + "张票");
}
}
取钱
package Multithreading;
public class UnsafeBank {
public static void main(String[] args) {
Account account = new Account(100,"零钱");
Drawing you = new Drawing(account,50,"你");
Drawing she = new Drawing(account,100,"她");
you.start();
she.start();
}
}
class Account{
int money;//余额
String name;//卡名
public Account(int money, String name) {
this.money = money;
this.name = name;
}
}
class Drawing extends Thread{
final Account account;
int drawingMoney;
int nowMoney;
public Drawing(Account account,int drawingMoney,String name){
super(name);
this.account = account;
this.drawingMoney = drawingMoney;
}
@Override
public synchronized 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.name+"余额为:"+account.money);
System.out.println(this.getName()+"手里的钱:"+nowMoney);}
}
}
添加数组
package Multithreading;
import java.util.ArrayList;
import java.util.List;
public class UnsafeList {
public static void main(String[] args) throws InterruptedException {
List<String> list = new ArrayList<>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{synchronized (list){list.add(Thread.currentThread().getName());}
}).start();
}
Thread.sleep(100);
System.out.println(list.size());
}
}
package Multithreading;
import java.util.concurrent.CopyOnWriteArrayList;
//测试JUC安全类型的集合
public class TestJUC {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
package Multithreading;
public class DeadLock {
public static void main(String[] args) {
Makeup g1 = new Makeup(0,"灰姑娘");
Makeup g2 = new Makeup(1,"白雪公主");
g1.start();
g2.start();
}
}
class Lipstick{
}
class Mirror{
}
class Makeup extends Thread {
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choice;
String girlName;
Makeup(int choice,String name){
this.choice = choice;
this.girlName = name;
}
@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){//1秒后获得镜子的锁
System.out.println(this.girlName+"获得镜子的锁");
}
}
else {
synchronized(mirror) {//获得镜子的锁
System.out.println(this.girlName + "获得镜子的锁");
Thread.sleep(2000);
}
synchronized(lipstick){//2秒后获得口红的锁
System.out.println(this.girlName+"获得口红的锁");
}
}
}
}
生产者消费者模式
package Multithreading;
//测试:生产者消费者模型-->利用缓冲区解决:管程法
public class TestPC {
public static void main(String[] args) {
SynContainer synContainer = new SynContainer();
new Productor(synContainer).start();
new Consumer(synContainer).start();
}
}
//生产者
class Productor extends Thread {
SynContainer synContainer;
public Productor(SynContainer synContainer){
this.synContainer = synContainer;
}
//生产
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("生产了"+i+"个产品");
synContainer.push(new Product(i));
}
}
}
//消费者
class Consumer extends Thread{
SynContainer synContainer;
public Consumer(SynContainer synContainer){
this.synContainer = synContainer;
}
//消费
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消费了"+synContainer.pop().id+"个产品");
}
}
}
//产品
class Product extends Thread{
int id;
public Product(int id){
this.id = id;
}
}
//缓冲区
class SynContainer{
//容器大小
Product[] products = new Product[10];
int size = 0;
//生产者放入产品
public synchronized void push(Product product){
//如果容器满了,就需要等待消费者消费
if(size==products.length){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//若没有满,则放入产品
products[size++] = product;
this.notifyAll();
}
public synchronized Product pop(){
//判断能否消费
if(size==0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//若可以消费
size--;
Product product =products[size];
//通知生产者生产
this.notifyAll();
return product;
}
}
package Multithreading;
//信号灯法:标志位
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.play("快乐大本营播放中");
} else {
this.tv.play("抖音:记录美好生活");
}
}
}
}
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{
//演员表演,观众等待 true
//观众观看,演员等待 false
String program;//表演的节目
boolean flag = true;
//表演
public synchronized void play(String program){
if (!flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演员表演了:"+program);
//通知观众观看
this.notifyAll();
this.program = program;
this.flag = !flag;
}
//观看
public synchronized void watch(){
if (flag){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观看了:"+program);
//通知演员表演
this.notifyAll();
this.flag = !flag;
}
}
package Multithreading;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestPool {
public static void main(String[] args) {
//1.创建服务,线程池
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());
}
}
原文:https://www.cnblogs.com/PxxxJ/p/14877674.html