JavaSE基础语法之多线程06

线程的创建

  • 继承Thread类

public class TestThread1 extends Thread{

    //重写run方法,调用start开启线程
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("我在看代码---" + i);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        //主线程
        TestThread1 testThread1 = new TestThread1();
        testThread1.start();

        for (int i = 0; i < 100; i++) {
            System.out.println("我在学习多线程" + i);
            sleep(5);
        }
    }
}
  • 实现Runnable接口

public class TestThread2 implements Runnable{    
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("我在看代码---" + i);
        }
    }

    public static void main(String[] args) throws InterruptedException {

        //创建Runnable接口的实现类
        TestThread2 testThread2 = new TestThread2();

        //创建线程对象,通过线程对象开启线程
        Thread thread = new Thread(testThread2);
        thread.start();

        for (int i = 0; i < 100; i++) {
            System.out.println("我在学习多线程" + i);
        }
    }
}
  • 实现Callable接口(了解)

public class TestCallable implements Callable {
    @Override
    public Boolean call() throws Exception {
        for (int i = 0; i < 100; i++) {
            System.out.println("我在看代码---" + i);
        }
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable testCallable1 = new TestCallable();
        TestCallable testCallable2 = new TestCallable();
        TestCallable testCallable3 = new TestCallable();

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

        //提交执行
        Future<Boolean> r1 = ser.submit(testCallable1);
        Future<Boolean> r2 = ser.submit(testCallable2);
        Future<Boolean> r3 = ser.submit(testCallable3);

        //获取结果
        boolean rs1 = r1.get();
        boolean rs2 = r2.get();
        boolean rs3 = r3.get();

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

线程常用方法

  • Thread.sleep() 休眠
  • Thread.yield() 礼让 不一定礼让成功
  • Thread.join() 合并线程 可理解为插队
  • Thread.setPriority() 设置线程优先级
  • Thread.getPriority() 获取线程优先级
  • Thread.setDaemon(true) 设置守护线程,默认是false
  • this.wait()
  • this.notifyAll()

案例:龟兔赛跑

/*
龟兔赛跑
1.赛道距离,离终点越来越近
2.判断比赛是否结束
3.打印出胜利者
4.启动比赛
5.模拟兔子睡觉
6.最终乌龟赢得比赛
 */
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();

    }
}

线程同步

  • 同步方法 synchronized,默认锁的是this

案例:多人买票问题

public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();

        new Thread(buyTicket, "张三").start();
        new Thread(buyTicket, "李四").start();
        new Thread(buyTicket, "王五").start();

    }
}

class BuyTicket implements Runnable{
    //票
    private int ticketNums = 10;
    boolean flag = true;   //外部停止方式

    @Override
    public void run() {
        //买票
        while (true){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    private synchronized void buy() throws InterruptedException {
        //判断是否有票
        if (ticketNums <= 0){
            flag = false;
            return;
        }

        //模拟延时
        Thread.sleep(100);
        //买票
        System.out.println(Thread.currentThread().getName() + "拿到" + ticketNums--);
    }
}

输出结果:
在这里插入图片描述

  • 同步块 synchronized(Obj){}

线程死锁

  • Lock锁解决 private final ReentrantLock lock= new ReentrantLock()
  • lock.lock() 加锁
  • lock.unlock() 解锁

生产者消费者问题–管程法

//生产者消费者模型-->利用缓冲区法解决:管程法

//生产者、消费者、缓冲区、产品
public class TestPC {
    public static void main(String[] args) {
        Buffer buffer = new Buffer();

        Productor productor = new Productor(buffer);
        Consumer consumer = new Consumer(buffer);

        productor.start();
        consumer.start();
    }
}

//生产者
class Productor extends Thread{
    Buffer buffer;

    public Productor( Buffer buffer) {
        this.buffer = buffer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            buffer.push(new Product(i));
            System.out.println("生产了" + i + "个产品");
        }
    }
}

//消费者
class Consumer extends Thread{
    Buffer buffer;

    public Consumer(Buffer buffer) {
        this.buffer = buffer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println("消费了" + buffer.pop().id + "个产品");

        }
    }
}

//产品
class Product{
    int id;

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

//缓冲区
class Buffer{
    //缓冲区大小
    Product[] products = new Product[10];
    int count = 0;

    //生产者放入产品
    public synchronized void push(Product product){
        //判断能否放入产品
        if(count == products.length){
            //等待消费者消费
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果缓冲区没满就可以放入产品
        products[count] = product;
        count++;

        //通知消费者消费
        this.notifyAll();
    }

    //消费者取出产品
    public synchronized Product pop(){
        //判断能否消费
        if (count == 0){
            //等待生产者放入
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //如果缓冲区不空就可以消费
        count--;
        Product product = products[count];

        //通知生产者生产
        this.notifyAll();
        
        return product;
    }
}

JavaSE入门: JavaSE基础语法01
JavaSE入门: JavaSE基础语法之面向对象和异常02
JavaSE入门: JavaSE基础语法之常见类03
JavaSE入门: JavaSE基础语法之集合框架04
JavaSE入门: JavaSE基础语法之I/O流05

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值