Java线程学习
1. 订票系统
提出问题:多个线程操作同一个资源的情况下,线程不安全,数据紊乱
package TicketServer;
//多个线程同时操作同一个对象
//买火车票的例子
//问题:多个线程操作同一个资源的情况下,线程不安全,数据紊乱
public class Thread1 implements Runnable{
//票数
private int ticketNums = 10;
@Override
public void run() {
while(true) {
if (ticketNums<=0) {
break;
}
//模拟延时
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNums--+"票");
}
}
public static void main(String[] args) {
Thread1 ticket = new Thread1();
new Thread(ticket,"lys").start();
new Thread(ticket,"cc").start();
new Thread(ticket,"yellow bull").start();
}
}
2. 龟兔赛跑
package Race;
//模拟龟兔赛跑
public class Race implements Runnable{
//胜利者
private static String winner;
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
//判断比赛是否结束
boolean flag = gameOver(i);
System.out.println(Thread.currentThread().getName()+"跑了"+i+"步数");
//如果比赛结束,就停止程序
if(flag) {
break;
}
}
}
//判断是否完成比赛
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;
}else {
return false;
}
}
public static void main(String[] args) {
Race race = new Race();
new Thread(race,"Rat").start();
new Thread(race,"Tortle").start();
}
}
3.静态代理
模式
/**
* 静态代理模式总结:
* 真实对象和代理对象都要实现同一个接口
* 代理对象要代理真实角色
* 好处:
* 代理对象可以做真实对象做不了的事情
* 真实对象可以做自己的事情
* @author ChangChen
*
*/
public class StaticProxy {
public static void main(String[] args) {
You you = new You();//你要结婚
new Thread( ()->System.out.println("i love you")).start();
WeddingCompany weddingCompany = new WeddingCompany(you);
weddingCompany.HappyMarry();
}
}
interface Marry{
//人间四大喜事
//久旱逢甘霖
//他乡遇故知
//洞房花烛夜
//金榜提名时
void HappyMarry();
}
//真实角色,你去结婚
class You implements Marry{
public void HappyMarry() {
System.out.println("Kim is going to be married!");
}
}
//代理角色,帮助你结婚
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("结婚前,布置现场");
}
}
4. Lambda 表达式
package lamda;
public class Lamda {
//3.静态内部类
static class Like2 implements ILike{
@Override
public void lamda() {
System.out.println("I like lamda2");
}
}
public static void main(String[] args) {
ILike like = new Like();
like.lamda();
like = new Like2();
like.lamda();
//4.局部内部类
class Like3 implements ILike{
@Override
public void lamda() {
System.out.println("I like lamda3");
}
}
like = new Like3();
like.lamda();
//5,匿名内部类,没有类的名称,必须借助接口或者父类
like = new ILike() {
@Override
public void lamda() {
System.out.println("I like lamda4");
}
};
like.lamda();
//6. Lambda简化
like = ()-> {
System.out.println("I like lamda5");
};
like.lamda();
}
}
//1.定义一个函数式接口:任何接口,如果只包含唯一一个抽象方法,那么它就是一个函数时接口
interface ILike{
void lamda();
}
//2.实现类
class Like implements ILike{
@Override
public void lamda() {
System.out.println("I like lamda");
}
}
package lamda;
public class Lamda2 {
public static void main(String[] args) {
ILove love = null;
//1。Lambda 表示简化
love = (int a/*, int b,int c*/)-> {
System.out.println("i love you-->"+ a);
};
//简化1:参数类型
love = (a/*,b,c*/)-> {
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);
//总结:
//lambda表达式只能有一行代码的情况下才能简化为一行,如果有多行,那么就用代码块包裹
//前提式接口为函数式接口
//多个参数也可以去掉参数类型,要去掉就都去掉
love.love(520/*,502,250*/) ;
}
}
interface ILove{
void love(int a);
}
5.线程的停止
package testStop;
//测试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);
//调用stop方法切换标志位,让线程停止
if(i==900) {
testStop.stop();
System.out.println("线程停止了");
}
}
}
}
6. 线程休眠_sleep
package testStop;
import java.text.SimpleDateFormat;
import java.util.Date;
//模拟倒计时
public class TestSleep {
public static void main(String[] args) {
try {
countDown();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void countDown() throws InterruptedException {
int num = 10;
while(true) {
Thread.sleep(1000);
System.out.println(num--);
if(num<0) {
break;
}
}
}
}
7.线程礼让_yield
//测试礼让线程
//礼让不一定成功
public class TestYield {
public static void main(String[] args) {
MyYield yield = new MyYield();
new Thread(yield,"a").start();
new Thread(yield,"b").start();
}
}
class MyYield implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"线程开始执行");
Thread.yield();//礼让
System.out.println(Thread.currentThread().getName()+"线程停止执行");
}
}
8.线程强制执行(插队)_join
//测试join方法
//想象为插队
public class TestJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 1000; 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 < 500; i++) {
if(i==200) {
thread.join();
}
System.out.println("main"+i);
}
}
}
9.线程的六个状态
//观察测试线程的状态
public class TestState {
public static void main(String[] args) {
Thread thread = new Thread(()->{
for (int i = 0; i < 2; i++) {
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("///");
});
//观察状态
Thread.State state = thread.getState();
System.out.println(state);//New
//观察启动后
thread.start();
thread.getState();
System.out.println(state);//Run
while(state!=Thread.State.TERMINATED) {
//只要线程不中止,就一直输出状态
state = thread.getState();//更新线程状态
System.out.println(state);//输出状态
}
}
}
10.线程优先级
//测试线程的优先级
public class TestPriority {
public static void main(String[] args) {
//主线程默认优先级为5
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(11);
// t4.start();
t4.setPriority(Thread.MIN_PRIORITY);
t4.start();
// t5.setPriority(-1);
// t5.start();
t6.setPriority(Thread.MAX_PRIORITY);
t6.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
}
}
11. 守护(daemon)线程
JVM必须确保用户线程执行完毕,JVM不用等待守护线程执行完毕
//测试守护线程
//上帝守护你
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 表示是用户线程, 正常的线程都是用户线程
thread.start();//上帝守护线程启动
new Thread(you).start();//你 用户线程开始...
}
}
//你
class You implements Runnable{
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("你正过一生");
}
System.out.println("----Ciao!---");
}
}
//上帝
class God implements Runnable{
@Override
public void run() {
while(true) {
System.out.println("May the Force be with you!");
}
}
}
12. 线程的同步
每个线程都在自己的工作内存交互,内存控制不当会造成数据不一致
package Concurrent;
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket station = new BuyTicket();
new Thread(station, "CC").start();
new Thread(station, "LYS").start();
new Thread(station, "Yellow Bull").start();
}
}
class BuyTicket implements Runnable{
//ticket
private int ticketNums = 10;
boolean flag = true;//外部停止方式
@Override
public void run() {
//buy tickets
while(flag) {
buy();
}
}
//synchronized 同步方法修饰
private synchronized void buy() {
//判断是否有票
if(ticketNums<=0) {
flag = false;
return;
}
//模拟延时
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//买票
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}
package Concurrent;
//不安全取钱
//两个人去银行取钱,账户
public class UnsafeBank {
public static void main(String[] args) {
Account account = new Account(1000,"结婚基金");
Drawing you = new Drawing(account,50,"你");
Drawing gf = new Drawing(account,100,"GF");
you.start();
gf.start();
}
}
//账户
class Account {
int money;//余额
String name;//卡名
public Account(int money, String name) {
super();
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(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
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);
}
}
}
package Concurrent;
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(()->{
synchronized (list) {
list.add(Thread.currentThread().getName());
}
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(list.size());
}
}
package Concurrent;
import java.util.concurrent.CopyOnWriteArrayList;
//测试JUC安全类型的集合
public class TestJUC {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
13. 死锁
package Concurrent;
//死锁:多个线程互相抱着对方需要的资源,然后形成僵持
public class DeadLock {
public static void main(String[] args) {
MakeUp g1 = new MakeUp(0,"sara");
MakeUp g2 = new MakeUp(1,"tiff");
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() {
//化妆
makeup();
}
//互相持有对方的锁,就是需要对方的资源
private void makeup() {
if(choice==0) {
synchronized (lipstick) {//获得口红的锁
System.out.println(this.girlName+"获得口红的锁");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
synchronized (mirror) {//一秒钟后获得镜子
System.out.println(this.girlName+"获得镜子的锁");
}
}else {
synchronized (mirror) {//获得镜子的锁
System.out.println(this.girlName+"获得镜子的锁");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
synchronized (lipstick) {//两秒钟后获得口红
System.out.println(this.girlName+"获得口红的锁");
}
}
}
}
14.Lock(锁)
可重入锁ReentrantLock 显式锁
package Concurrent;
import java.util.concurrent.locks.ReentrantLock;
//测试Lock锁
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 = 10;
//定义lock锁
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while(true) {
try {
lock.lock();
if(ticketNums>0) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(ticketNums--);
}else {
break;
}
} catch (Exception e) {
// TODO: handle exception
}finally {
//解锁
lock.unlock();
}
}
}
}
15.线程协作:生产者消费者问题
管程法
//测试生产者消费者模型-->利用缓冲区解决:管程法
//生产者,消费者,产品,缓冲区
public class TestPC {
public static void main(String[] args) {
SynContainer container = new SynContainer();
new Productor(container).start();
new Consumer(container).start();
}
}
//生产者
class Productor extends Thread{
SynContainer container;
public Productor(SynContainer container) {
this.container=container;
}
@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;
}
@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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//如果没有满,我们就需要丢入产品
chickens[count]=chicken;
count++;
//可以通知消费者消费产品
this.notifyAll();
}
public synchronized Chicken pop() {
//判断能否消费
if(count==0) {
//等待生产者生产,消费者等待
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//如果可以消费
count--;
Chicken chicken = chickens[count];
//吃完了,通知生产者生产
this.notifyAll();
return chicken;
}
}
信号灯法
//测试生产者消费者问题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{
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("Netflix");
}else {
this.tv.play("Donald Trump BroadCast");
}
}
}
}
//消费者-->观众
class Watcher extends Thread{
TV tv;
public Watcher(TV tv) {
super();
this.tv = tv;
}
@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) {
// TODO Auto-generated catch block
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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("观看了:"+voice);
//通知演员表演
this.notifyAll();
this.flag = !this.flag;
}
}
16. 线程池
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());
service.execute(new MyThread());
//3.关闭链接
service.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}