java多线程

java多线程

1.1、进程

程序:指令和数据的有序集合,是一个静态的概念。

进程:一次执行程序的过程,是一个动态的概念。

​ 一个进程可以包含若干个线程,至少包含一个线程,线程是CPU调度和执行的单位。

1.2、线程创建

三种方式

​ 继承Thread类

package com.thomas.lesson01;
//线程开启不一定立即执行,由CPU调度执行
public class TestThread1 extends Thread{
    //继承thread类,重写run方法
    @Override
    public void run() {
        //run方法线程体
        for (int i = 0;i < 8;i++) {
            System.out.println("我在看代码:"+i);
        }
    }
    public static void main(String[] args) {
        TestThread1 testThread1 = new TestThread1();
        testThread1.start();
        //main线程,主线程
        for (int i = 0;i < 5;i++) {
            System.out.println("我在学习多线程:"+i);
        }
    }
}

​ 实现Runnable接口

package com.thomas.lesson01;

public class TestThread3 implements Runnable {
    @Override
    public void run() {
        //run方法线程体
        for (int i = 0;i < 8;i++) {
            System.out.println("我在看代码:"+i);
        }
    }

    public static void main(String[] args) {
        TestThread3 testThread3 = new TestThread3();
        new Thread(testThread3).start();
        //main线程,主线程
        for (int i = 0;i < 5;i++) {
            System.out.println("我在学习多线程:"+i);
        }
    }
}

​ 实现Callable接口

package com.thomas.lesson01;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;

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() throws Exception {
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downLoader(url,name);
        System.out.println("下载了"+name);
        return true;
    }
    public static void main(String[] args) {
        TestCallable t1 = new TestCallable("https://commons.apache.org/proper/commons-io/images/commons-logo.png","阿帕奇.png");
        TestCallable t2 = new TestCallable("https://www.apache.org/events/current-event-125x125.png","阿帕.png");
        TestCallable t3 = new TestCallable("https://maven.apache.org/images/logos/maven-feather.png","阿.png");
        //创建执行服务
        ExecutorService ser = Executors.newFixedThreadPool(3);
        //提交执行
        Future<Boolean> r1 = ser.submit(t1);
        Future<Boolean> r2 = ser.submit(t2);
        Future<Boolean> r3 = ser.submit(t3);
        //获取结果
        try {
            boolean rs1 = r1.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        try {
            boolean rs2 = r2.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        try {
            boolean rs3 = r3.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        //关闭服务
        ser.shutdownNow();
    }
}

1.3、静态代理

可以实现本身不需要实现的细节。

真实对象专注实现必须由对象本身完成的细节。

1.4、线程状态

停止线程

package com.thomas.lesson02;

import java.util.concurrent.atomic.AtomicBoolean;

public class TestStop implements Runnable{
    //设置一个标志位
    private AtomicBoolean flag = new AtomicBoolean(true);
    @Override
    public void run() {
        int i = 0;
        while (flag.get()) {
           //存在线程偷跑情况
            System.out.println("run...Thread"+i++);
        }
    }
    public void stop() {
        flag.set(false);
    }

    public static void main(String[] args) {
        TestStop ts = new TestStop();
        new Thread(ts).start();
        for (int i = 0; i < 15; i++) {
            System.out.println("当前线程位"+i);
            if (i==10) {
                ts.stop();
                System.out.println("线程该停止了");
            }
        }
    }
}

线程休眠

​ 每一个对象都有一个锁,sleep不会释放这个锁。

package com.thomas.lesson01;
//买票的例子,多个线程运行一个实例

//多个线程操作同一资源线程不安全,数据紊乱
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();
    }
}

线程礼让

​ 让当前正在执行的线程暂停,但不阻塞。

​ 将线程从运行状态转为就绪状态。

package com.thomas.lesson02;
//线程礼让不一定成功,主要还是看CPU调度情况
public class YieldTest {
    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()+"线程停止执行");
    }
}

java多线程10:44

线程阻塞

强行停止线程,让其他线程先执行。

package com.thomas.lesson02;

public class JoinTest implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 600; i++) {
            System.out.println("vip执行第"+i+"次。");
        }
    }

    public static void main(String[] args) {
        JoinTest joinTest = new JoinTest();
        Thread thread = new Thread(joinTest);
        thread.start();
        for (int i = 0; i < 300; i++) {
            if (i==150) {//主线程运行到第一百五被阻塞
                try {
                    thread.join();//线程阻塞
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("这是第"+i+"次。");
        }
    }
}

java多线程11:06

观测线程状态

package com.thomas.lesson02;

import java.util.concurrent.ThreadFactory;

//监测线程状态
public class StateTest implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println("----------");
    }

    public static void main(String[] args) {
        StateTest stateTest = new StateTest();
        Thread thread = new Thread(stateTest);
        Thread.State state = thread.getState();
        System.out.println(state);//未启动状态
        thread.start();
        //每次都要更新状态
        state = thread.getState();
        System.out.println(state);//启动
        while (!state.equals(Thread.State.TERMINATED)) {
            try {
                Thread.sleep(600);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            state = thread.getState();
            System.out.println(state);
        }
    }
}

java多线程11:30

线程优先级

线程优先级从1-10

-Thread.NORM_PRIORITY(5)

-Thread.MIN_PRIORITY(1)

-Thread.MAX_PRIORITY(10)

package com.thomas.lesson02;
//设置线程优先级可以提升线程被CPU优先调度的概率
public class PriorityTest {
    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);
        t1.setPriority(Thread.MIN_PRIORITY);//默认MIN_PRIORITY=0
        t1.start();
        t2.setPriority(3);
        t2.start();
        t3.setPriority(Thread.MAX_PRIORITY);//默认MAX_PRIORITY=10
        t3.start();
    }
}
class MyPriority implements Runnable {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
    }
}

java多线程11:57

守护线程

虚拟机会确保用户线程执行完毕,而不会等待守护线程执行完毕。

package com.thomas.lesson02;

public class DaemonTest {
    public static void main(String[] args) {
        You you = new You();
        Defend defend = new Defend();
        Thread thread = new Thread(defend);
        thread.setDaemon(true);
        thread.start();
        new Thread(you).start();
    }

}
class Defend implements Runnable {
    @Override
    public void run() {
        while(true){
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("我会一直守护着你,直到永远!");
        }
    }
}
class You implements Runnable {
    @Override
    public void run() {
        for (int i = 0; i < 365; i++) {
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("这是今年的第"+ i +"天。");
        }
        System.out.println("明年见。");
    }
}

java多线程14:32

为了少数出内容对比强烈加了线程休眠,在用户线程结束的时候不论守护线程有没有中止条件都会终止,没加休眠的情况下,在程序运行结束虚拟机关闭的状态进行时,守护线程还会正常运行直到虚拟机完全关闭。

1.5、线程同步机制

并发

​ 多个线程想要同时访问一个资源时。

同步

​ 多个线程同时访问一个对象,让线程按顺序访问这个对象。

线程锁

​ 线程获得对象的排他锁,就可以独占资源。

1.6、同步方法同步块

同步方法synchronized

​ 可能会给不需要仅读取的资源加锁,造成资源浪费。

synchronized(同步对象){}

public class SafeList {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();//并发编程的线程安全列表CopyOnWriteArrayList
        for (int i = 0; i < 10000; i++) {
            new Thread(() -> {
                // 给使用add()方法的对象list加同步锁,保证同一时刻只有一个线程执行add()
                synchronized (list) {
                    list.add(Thread.currentThread().getName());
                }
            }).start();
        }
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(list.size()); // 此时结果会是10000
    }
}

2.1、死锁

死锁

​ 多个线程同时占有一些资源,产生两个或多个线程同时等待对方线程释放资源而停止运行的情况。

package com.thomas.lesson03;

public class DeadLock {
    public static void main(String[] args) {
        Makeup girl1 = new Makeup("girl1",0);
        Makeup girl2 = new Makeup("girl2",1);
        girl1.start();
        girl2.start();
    }
}
class Mirror {
}
class LipStick {
}
class Makeup extends Thread {
    //唯一的镜子对象
    static Mirror mirror = new Mirror();
    static LipStick lipStick = new LipStick();
    private String name;
    private int choice;
    public Makeup(String name, int choice) {
        this.name = name;
        this.choice = choice;
    }
    @Override
    public void run() {
        makeup();
    }
    private  void makeup() {
        if (choice==0) {
            //获得镜子1秒后获得口红
            synchronized (mirror) {
                System.out.println(this.name+"-->"+"获得了镜子。");
                try {
                    Thread.sleep(1000);
                    synchronized (lipStick) {
                        System.out.println(this.name+"-->"+"获得了口红。");
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }else {
            //获得口红三秒后获得镜子
            synchronized (lipStick) {
                System.out.println(this.name+"-->"+"获得了口红。");
                try {
                    Thread.sleep(3000);
                    synchronized (mirror) {
                        System.out.println(this.name+"-->"+"获得了镜子。");
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

2.2、可重入锁

package com.thomas.advanced;

import java.util.concurrent.locks.ReentrantLock;

//通过ReentrantLock 可重入锁实现线程同步机制
public class LockTest {
    public static void main(String[] args) {
        NewLock newLock = new NewLock();
        new Thread(newLock).start();
        new Thread(newLock).start();
        new Thread(newLock).start();
    }
}
class NewLock implements Runnable {
private int ticketNums = 10;
private ReentrantLock lock = new ReentrantLock();
    @Override
    public void run() {
        while(true){
            try {
                lock.lock();//锁定
                if(ticketNums>0){
                    try {
                        //模拟线程交替
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println(ticketNums--);

                }else {
                    break;
                }
            }finally {
                lock.unlock();//解锁
            }
        }
    }
}

java多线程17:33

3.1线程通信

3.2、线程池

线程池

​ 提前创建好多个线程,放入线程池,避免频繁创建销毁、实现重复利用。

好处

​ 提高响应速度。

​ 降低资源消耗。

​ 便于线程管理(大小、数量、存在时间)。

package com.thomas.advanced;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class PoolTest {
    public static void main(String[] args) {
        //1.开启服务,创建线程池
        ExecutorService pool = Executors.newFixedThreadPool(5);
        //2.运行服务
        pool.execute(new MyThread());
        pool.execute(new MyThread());
        pool.execute(new MyThread());
        pool.execute(new MyThread());
        //3.关闭线程池
        pool.shutdownNow();
    }
}
class MyThread implements Runnable {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}

处理偶数数组(复习)

import java.util.ArrayList;
import java.util.List;

public class ArrayFilter {
    public int[] filterArray(int[] arr) {
        List<Integer> list = new ArrayList<>();
        for (int num : arr) {
            if (num % 2 == 0) {
                list.add(num);
            }
        }
        int[] newArr = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            newArr[i] = list.get(i);
        }
        return newArr;
    }
}

'流API'。

posted @ 2025-12-23 19:33  coldmist  阅读(3)  评论(0)    收藏  举报