多线程
重点:线程实现、线程同步
新生–>就绪–>阻塞–>运行–>死亡–>
Thread 线程
//创建线程方法一:继承THread类,重写run()方法,调用start方法开启线程
//总结:注意,线程开启不一定立即执行,有cpu调度执行
public class Text extends Thread{
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("我在看代码----");
}
}
public static void main(String[] args) {
//main线程, 主线程
//创建线程对象
Text text = new Text();
//开启线程start是交替执行
text.start();
for (int i = 0; i < 20; i++) {
System.out.println("我早");
}
}
}
//下载图片案例
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() {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url, name);
System.out.println("下载了文件名:"+name);
}
public static void main(String[] args){
TestThread2 t1 = new TestThread2("https://img-blog.csdnimg.cn/20200305081800551.jpg", "1.jpg");
TestThread2 t2 = new TestThread2("https://img-blog.csdnimg.cn/20200305082009840.jpg", "2.jpg");
t1.start();
t2.start();
}
}
//下载器
class WebDownloader{
//下载方法
public void downloader(String url, String name){
try {
FileUtils.copyURLToFile(new URL(url), new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常");
}
}
}
//创建线程方法2 ; 实现runnable接口,重写run方法, 执行线程需要丢入runnable接口实现类,调用start方法
public class TextThread3 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("下载了文件名:");
}
}
public static void main(String[] args){
//创建runnable接口的实现类对象
TextThread3 thread = new TextThread3();
//创建线程对象,通过线程对象来开启我们的线程,代理
new Thread(thread).start();
for (int i = 0; i < 1000; i++) {
System.out.println("我在学习----");
}
}
}
//多线程同时操作同一个对象
//买火车票的例子
//发现问题:多个线程操作同一个资源的情况下,线程不安全,数据紊乱,
public class TestThread4 implements Runnable{
//票数
int ticketNum = 10;
@Override
public void run() {
while(true){
if (ticketNum<=0){
break;
}
//模拟延时
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"-->拿到了"+ticketNum--+"票");
}
}
public static void main(String[] args) {
TestThread4 ticket = new TestThread4();
new Thread(ticket, "小明").start();
new Thread(ticket, "老师").start();
new Thread(ticket, "夯牛").start();
}
}
//模拟龟兔赛跑
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(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;
}{
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();
}
}
public class TestCallable implements Callable<Boolean> {
private String url;//保存图片地址
private String name;//保存的文件名
public TestCallable(String url, String name){
this.url = url;
this.name = name;
}
//下载图片线程的执行体
@Override
public Boolean call() {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url, name);
System.out.println("下载了文件名:"+name);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException{
TestCallable t1 = new TestCallable("https://img-blog.csdnimg.cn/20200305081800551.jpg", "1.jpg");
TestCallable t2 = new TestCallable("https://img-blog.csdnimg.cn/20200305082009840.jpg", "2.jpg");
//创建执行服务:
ExecutorService ser = Executors.newFixedThreadPool(2);
//提交执行
Future<Boolean> result1 = ser.submit(t1);
Future<Boolean> result2 = ser.submit(t2);
//获取结果
boolean rs1 = result1.get();
boolean rs2 = result2.get();
//关闭服务
ser.shutdownNow();
}
}
class WebDownloader{
//下载方法
public void downloader(String url, String name){
try {
FileUtils.copyURLToFile(new URL(url), new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常");
}
}
}
静态代理
//代理是线程底部实现原理
//静态代理模式总结:
//真实对象和代理对象都要实现同一个接口
//代理对象必须代理真实
//好处:
//代理对象可以做很多真实对象做不了的事情
//真实对象可以专注自己的事情
public class StacticProxy {
public static void main(String[] args) {
You you = new You();//你要结婚
WweddingCompany wenddingCompany = new WweddingCompany(new You());
wenddingCompany.HappyMarry();
}
}
interface Marry{ //接口
void HappyMarry();
}
//真实角色,你去结婚
class You implements Marry{
@Override
public void HappyMarry() {
System.out.println("我结婚了");
}
}
//代理角色, 帮助你结婚
class WweddingCompany implements Marry{
//代理-->真实目标角色
private Marry target;
public WweddingCompany(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表达式
函数式编程
/*
推导lamda表达式
*/
public class lamda1 {
public static void main(String[] args) {
ILike love = null;
System.out.println("得不到");
love = a -> System.out.println("i love wei" + a);
love.lamda(520);
}
}
//1、定义一个函数式接口、
interface ILike{
void lamda(int a);
}
//总结:
// lambda表达式只能有一行代码才能不用花括号
//前提:接口只能是函数式接口,接口中只能由一个方法
//多个参数也可以去掉参数类型,要去掉都去掉。但是必须加括号
//
线程停止
//测试stop
//1、建议线程正常停止--->利用次数,不建议死循环
//2、建议使用标志位--->设置一个标志位
//3、不要使用stop或者destroy等过时或者JDK不建议使用的方法
public class test_stop implements Runnable{
//1、设置一个标志位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while(flag){
System.out.println("runrun"+i++);
}
}
//2、设置一个公开的方法停止线程,转换标志位
public void stop(){
this.flag = false;
}
public static void main(String[] args) {
test_stop testStop = new test_stop();
new Thread(testStop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main"+i);
if(i==900){
//调用标志位让线程停止
testStop.stop();
System.out.println("线程停止了");
}
}
}
}
//模拟倒计时。。。
public class TestSleep {
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();
}
}
}
//模拟倒计时
public static void tenDown() throws InterruptedException {
int num = 10;
while(true) {
Thread.sleep(1000);
System.out.println(num--);
if (num<=0){
break;
}
}
}
}
//线程礼让
//礼让比一定成功,看CPU心情
强制执行 Jion
//测试join方法//想象插队
public class TestJion implements Runnable {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("vip来了");
}
}
public static void main(String[] args) throws InterruptedException {
//启动线程
TestJion testJion = new TestJion();
Thread thread = new Thread(testJion);
//主线程
for (int i = 0; i < 100; i++) {
if (i == 20){
thread.start();
thread.join();
}
System.out.println("main"+i);
}
}
}
测试线程状态
//观察测试线程状态
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);
//观察自动后
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 TestPriority {
public static void main(String[] args) {
//主线程默认优先级
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(4);
t2.start();
t3.setPriority(10);
t3.start();
t4.setPriority(1);
t4.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread()+"-->"+Thread.currentThread().getPriority());
}
}
线程守护
//测试守护线程
//上帝守护你
public class TestDsemon {
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 < 36500; i++) {
System.out.println("你一生都很开心的活着");
}
System.out.println("goodbye!world");
}
线程同步控制 并发
机制锁 synchronized
//不安全的买票
public class UnsafeBuyTicket {
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){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//synchronized 同步方法,锁的是this
private synchronized void buy() throws InterruptedException {
//判断是否有票
if(ticketNums<=0){
return;
}
//模拟延时
Thread.sleep(100);
//买票
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 wife = new Drawing(account, 100, "妻子");
you.start();
wife.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
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 +=drawingMoney;
System.out.println(account.name+"余额为:"+account.money);
//this.getName() = Thread.currentThread().getName()
System.out.println(this.getName()+"手里的钱"+nowMoney);
}
}
}
机制锁 同步块 synchronized
方法声明用synchronized大大降低了代码效率
JUC
//测试JUC安全类型的集合
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(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}
死锁
//死锁:多个线程互相抱着对方需要的资源,然后形成僵持
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来保证只有一份
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choice;//选择
String girlfriend;//使用化妆品的人
Makeup(int choice ,String girlfriend){
this.choice = choice;
this.girlfriend = girlfriend;
}
@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.girlfriend+"获得口红的锁");
Thread.sleep(1000);
}
synchronized (mirror){//一秒钟后想获得镜子
System.out.println(this.girlfriend+"获得镜子的锁");
}
}else {
synchronized (mirror){//获得镜子的锁
System.out.println(this.girlfriend+"获得镜子的锁");
Thread.sleep(1000);
}
synchronized (lipstick){//一秒钟后想获得口红
System.out.println(this.girlfriend+"获得口红的锁");
}
}
}
}
lock锁
lock显示的锁,手动打开,手动关闭 syn锁是隐式的,出了作用域自动释放
lock效果更好
//测试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) {
e.printStackTrace();
}
System.out.println(ticketNums--);
}else {
break;
}
}finally {
//解锁
lock.unlock();
}
}
}
}
线程通信
wait()#线程等待 会释放锁
notify()#唤醒处于等待状态的锁
方法一(管程法):