Java多线程

三种创建线程方式

( 一 )

package lesson3;

/**
 * 创建线程方法之一,继承Thread,并重写run()方法
 *  调用start()方法开启线程
 */
public class TestThread extends Thread{
    @Override
    public void run() {
        System.out.println("继承Thread的线程");
    }

    public static void main(String[] args) {
        TestThread tt = new TestThread();
        tt.start();
    }
}

( 二 ) 推荐使用实现Runnable接口创建线程

package lesson3;

/**
 * 创建线程的第二种方式 实现Runnable接口、
 * 将实现类对象放入Thread构造方法中
 */
public class TestRunnable implements Runnable {
    @Override
    public void run() {
        System.out.println("实现Runnable接口的线程");
    }

    public static void main(String[] args) {
        TestRunnable tr = new TestRunnable();
        Thread thread = new Thread(tr);
        thread.start();
    }
}

(三)

package lesson3;

import java.util.concurrent.*;

/**
 * 第三种实现线程方式
 * 实现Callable接口,并添加泛型
 * 重写call方法,有返回值
 */
public class TestCallable implements Callable<Boolean> {

    /*
    重写call()方法
     */
    @Override
    public Boolean call(){
        System.out.println("实现Callable接口线程");
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable   c1 = new TestCallable();
        TestCallable   c2 = new TestCallable();
        TestCallable   c3 = new TestCallable();

        //创建执行服务
        ExecutorService service = Executors.newFixedThreadPool(3);

        //提交执行
        Future<Boolean> result1 = service.submit(c1);
        Future<Boolean> result2 = service.submit(c2);
        Future<Boolean> result3 = service.submit(c3);

        //获取结果
        Boolean re1 = result1.get();
        Boolean re2 = result2.get();
        Boolean re3 = result3.get();

        //关闭服务
        service.shutdown();
    }
}

线程五大状态

在这里插入图片描述

线程阻塞 sleep()

package lesson3;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 线程休眠
 * sleep()不会释放锁
 */
public class TestSleep implements Runnable{
    @Override
    public void run() {
        //获取当前系统时间
        Date date = new Date(System.currentTimeMillis());
        while(true) {
            //格式化时间并输出
            System.out.println(new SimpleDateFormat("HH:mm:ss").format(date));
            //更新时间
            date = new Date(System.currentTimeMillis());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        TestSleep testSleep = new TestSleep();
        new Thread(testSleep).start();
    }

}

线程停止(建议使用标识位)

package lesson3;

/**
 * 测试Stop
 * 1.建议线程自动停止
 * 2.建议使用标志位 --> 设置一个标志位
 * 3.不要使用stop或者destroy等过时的方法
 */
public class TestStop implements Runnable{

    //设置一个标识位
    private boolean flag = true;

    @Override
    public void run() {
        int n = 0;
        while(flag){
            System.out.println("运行中"+n++);
        }
    }

    //设置一个公开的停止线程方法
    public void stop(){
        this.flag = false;
    }

    public static void main(String[] args) {
        TestStop ts = new TestStop();
        new Thread(ts).start();

        for (int i = 0; i < 1000; i++) {
            System.out.println(i);
            if(i==500) {
                //调用自己实现的停止方法
                ts.stop();
                System.out.println("线程已停止!");
                break;
            }
        }
    }
}

线程礼让 yield()

package lesson3;

/**
 * 线程礼让  yield()
 * 但不一定成功,礼让之后看cpu决定
 */
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()+"线程停止结束");
    }
}

线程插队 join()

package lesson3;

/**
 * 测试join方法
 * 相当于线程插队
 */
public class TestJoin implements Runnable {
    @Override
    public void run() {
        for (int i = 1; i < 100; i++) {
            System.out.println("vip线程执行了" + i + "次");
        }
    }
    
    public static void main(String[] args) {
        TestJoin join = new TestJoin();
        Thread thread = new Thread(join);
        thread.start();

        for (int i = 1; i < 500; i++) {
            if (i == 100) {
                try {
                    //线程插队
                    thread.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("主线程第" + i + "次");
        }
    }
}

线程的优先级

package lesson3;


/**
 * 测试线程的优先级
 * 一个线程的优先级高,但是并不一定会先执行
 * 高的优先级只是更大概率先被CPU执行
 * 优先级分为整数的 [1-10]
 * getPriority(int)
 * setPriority(int)
 */
public class TestPriority {

    public static void main(String[] args) {
        //主线程的默认优先级 = 5
        System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());

        MyPriority myPriority = new MyPriority();
        //创建5个线程
        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);

        //先设置优先级,再启动
        t1.setPriority(3);
        t2.setPriority(6);
        t3.setPriority(9);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();


    }

}

class MyPriority implements Runnable {

    @Override
    public void run() {
        /*
            获取线程的名字  Thread.currentThread().getName()
            获取线程的当前优先级  Thread.currentThread().getPriority()
         */
        System.out.println(Thread.currentThread().getName() + "-->" + Thread.currentThread().getPriority());
    }
}

用户线程 和 守护线程

package lesson3;

/**
 * 测试守护线程
 *
 * 线程分为 用户线程 和 守护线程
 * 用户线程一般就是自己创建的线程
 * 而GC就是守护线程
 * 虚拟机只确保用户线程执行完毕,守护线程会随着所有的用户线程停止而停止
 * setDaemon(true); 设置线程为守护线程 默认值是false
 */
public class TestDaemon {

    public static void main(String[] args) {
        User user = new User();
        Daemon daemon = new Daemon();

        //设置为守护线程
        Thread thread = new Thread(daemon);
        thread.setDaemon(true);
        thread.start();

        //启动用户线程
        new Thread(user).start();

    }
}

/**
 * 模拟用户线程
 */
class User implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 50; i++) {
            System.out.println("用户线程在执行...");
        }
        System.out.println("用户线程停止了!``````````````````");
    }
}

/**
 * 模拟守护线程
 */
class Daemon implements Runnable{
    @Override
    public void run() {
        for (int i = 0; i < 20; i++) {
            System.out.println("守护线程在执行...");
        }
    }
}

观测线程状态

package lesson3;

/**
 * 观测线程的状态
 *      NEW       创建
 *      RUNNABLE  运行中
 *      BLOCKED   阻塞
 *      WAITING   等待
 *      TIMED_WAITING
 *      TERMINATED 终止
 * Thread.State -> getState()
 */
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);

        while(state != Thread.State.TERMINATED){
            Thread.sleep(500);
            state = thread.getState();
            System.out.println(state);
        }
    }
}

线程同步

由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题﹐为了保证数据在方法中被访问时的正确性,在访问时加入锁机制synchronized ,当一个线程获得对象的排它锁,独占资源,其他线程必须等待,使用后释放锁即可.存在以下问题:
1.一个线程持有锁会导致其他所有需要此锁的线程挂起;
2.在多线程竞争下,加锁﹐释放锁会导致比较多的上下文切换和调度延时,引起性能问题;
3.如果一个优先级高的线程等待一个优先级低的线程释放锁会导致优先级倒置﹐引起性能问题

同步方法 public synchronized void method(…){}

synchronized方法控制对“对象”的访问,每个对象对应一把锁,每个synchronized方法都必须获得调用该方法的对象的锁才能执行,否则线程会阻塞,方法一旦执行,就独占该锁,直到该方法返回才释放锁,后面被阻塞的线程才能获得这个锁,继续执行
缺陷:若将一个大的方法申明为synchronized将会影响效

package lesson3;

/**
 * 多个线程操作同一个对象
 * 例如 : 买票
 */
public class TestRunnable2 implements Runnable {

    //票
    private Integer k = 20;

    //标识位
    private boolean flag = true;

    @Override
    public void run() {
        while (flag) {
            //模拟网络延时 毫秒
            //放大问题的发生性
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //买票
            this.buy();
        }
    }

    //锁的是this
    public synchronized void buy() {
        if (k <= 0) {
            flag = false;
            return;
        }
        //Thread.currentThread().getName()获取线程名字
        System.out.println(Thread.currentThread().getName() + "买到了第" + k-- + "张票");
    }

    public static void main(String[] args) {
        TestRunnable2 tr = new TestRunnable2();

        new Thread(tr, "小明").start();
        new Thread(tr, "李四").start();
        new Thread(tr, "张三").start();

    }
}

同步块 synchronized(Object){ }

同步块: synchronized (Object ){ }
Object称之为同步监视器,Object可以是任何对象﹐但是推荐使用共享资源作为同步监视器
同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this ,就是这个对象本身,或者是class
同步监视器的执行过程
1.第一个线程访问﹐锁定同步监视器﹐执行其中代码
2.第二个线程访问,发现同步监视器被锁定﹐无法访问
3.第一个线程访问完毕,解锁同步监视器
4.第二个线程访问,发现同步监视器没有锁﹐然后锁定并访问

//
synchronized(Object){ 
		//代码
}

死锁

多个线程各自占有一些共享资源,并且互相等待其他线程占有的资源才能运行,而导致两个或者多个线程都在等待对方释放资源,都停止执行的情形,某一个同步块同时拥有“两个以上对象的锁”时,就可能会发生“死锁”的问题

产生死锁的四个必要条件:
1.互斥条件:一个资源每次只能被一个进程使用。
2.请求与保持条件:一个进程因请求资源而阻塞时,对已获得的资源保持不放。
3.不剥夺条件∶进程已获得的资源,在末使用完之前,不能强行剥夺。
4.循环等待条件:若干进程之间形成一种头尾相接的循环等待资源关系。

Lock(锁)

1.从JDK 5.0开始,Java提供了更强大的线程同步机制——通过显式定义同步锁对象来实现同步。同步锁使用Lock对象充当
2.java.util.concurrent.locks.Lock接口是控制多个线程对共享资源进行访问的工具。锁提供了对共享资源的独占访问,每次只能有一个线程对Lock对象加锁,线程开始访问共享资源之前应先获得Lock对象
3.ReentrantLock类实现了Lock,它拥有与synchronized相同的并发性和内存语义,在实现线程安全的控制中,比较常用的是ReentrantLock,可以显式加锁、释放锁。

package lesson3;

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 {

    private int ticket = 20;
    //定义Lock锁
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (true) {
            try{
                //加锁
                lock.lock();
                if (ticket > 0) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("票剩余" + ticket--);
                } else break;
            }finally{
                //解锁
                lock.unlock();
            }

        }
    }
}

synchronized 与 Lock 对比

1.Lock是显式锁(手动开启和关闭锁) synchronized是隐式锁,出了作用域自动释放
2.Lock只有代码块锁,synchronized有代码块锁和方法锁
3.使用Lock锁,JVM将花费较少的时间来调度线程,性能更好。并且具有更好的扩展性(提供更多的子类)

线程通信问题(生产者和消费者模式问题)

在这里插入图片描述

在这里插入图片描述

package lesson3;

/**
 * 测试:生产者消费者模型-->管城法
 * 生产者
 * 消费者
 * 产品
 * 缓冲区
 */
public class TestPC {

    public static void main(String[] args) {
        //创建容器
        SynContainer synContainer = new SynContainer();

        //创建生产者
        new Producer(synContainer).start();
        //创建消费者
        new Consumer(synContainer).start();
    }
}

/**
 * 生产者
 */
class Producer extends Thread {

    //容器
    SynContainer synContainer;

    public Producer(SynContainer synContainer) {
        this.synContainer = synContainer;
    }

    /*
        生产者生产
     */
    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            synContainer.push(new Chicken(i));
            System.out.println("生产了" + i + "鸡");
        }
    }
}

/**
 * 消费者
 */
class Consumer extends Thread {

    //容器
    SynContainer synContainer;

    public Consumer(SynContainer synContainer) {
        this.synContainer = synContainer;
    }

    /*
        消费者消费
     */
    @Override
    public void run() {
        for (int i = 1; i < 100; i++) {
            System.out.println("消费了第" + synContainer.pop().id + "只鸡");
        }
    }
}

/**
 * 产品
 */
class Chicken {
    int id = 0;

    public Chicken(int id) {
        this.id = id;
    }
}

/**
 * 缓冲区 容器
 */
class SynContainer {

    //定义一个容器
    Chicken[] chickens = new Chicken[10];

    //容器计数器
    int count = 0;

    //把产品放入容器
    public synchronized void push(Chicken chicken) {
        //如果容器满了,就等待
        if (chickens.length == count) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果容器没满,就生产
        chickens[count++] = chicken;

        //唤醒消费者
        this.notifyAll();
    }

    //从容器取出产品
    public synchronized Chicken pop() {
        //判断容器是否有产品
        if (count == 0) {
            try {
                //等待生产者生产
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //有产品就消费
        Chicken chicken = chickens[--count];

        //产品消费完了,唤醒生产者
        this.notifyAll();
        return chicken;
    }
}



在这里插入图片描述

package lesson3;

/**
 * 测试:生产者消费者模型-->信号灯法
 * 通过标志位解决
 */
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++) {
            this.tv.watch();
        }
    }
}

/**
 * 产品  节目
 */
class TV {
    //演员表演,观众等待
    //观众观看,演员等待

    //表演节目
    String voice;
    //标志位
    boolean flag = true;

    //表演
    public synchronized void play(String voice) {
        if (!flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("演员表演了:" + voice);

        //通知观众观看
        this.notifyAll();
        this.voice = voice;
        flag = !flag;
    }

    //观看
    public synchronized void watch() {
        if (flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("观众观看了:" + voice);

        this.flag = !flag;

        //通知演员表演
        this.notifyAll();
    }
}

线程池的使用和创建

在这里插入图片描述
在这里插入图片描述

package lesson3;

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

/**
 *  测试线程池
 */
public class TestPool {

    public static void main(String[] args) {
        //创建服务 创建线程池
        //newFixedThreadPool 参数为:线程池大小
        ExecutorService service = Executors.newFixedThreadPool(10);

        //执行实现的线程
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());
        service.execute(new MyThread());

        //关闭连接
        service.shutdown();
    }

}

class MyThread implements Runnable{
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Oak Coffee

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值