20/365 java 多线程(二) 实现Runnable接口

文章展示了如何在Java中通过实现Runnable接口创建线程,强调了这种方式能避免单继承的限制并允许线程共享对象。通过一个糖果分配的例子,说明了多线程并发可能引发的资源竞争问题。此外,文章还提供了用多线程实现龟兔赛跑的代码示例,强调每个线程有自己的局部变量和独立执行的特点。
摘要由CSDN通过智能技术生成

1.实现Runnable接口来创建线程

创建一个类implements Runnable

重写run()方法

public class D9 implements Runnable{
    public void run() {
        int n = 100;
        for(int i=0;i<n;i++){
            System.out.println("This is thread D9  " + i);
        }
    }
}

创建Thread类(用该类对象作为参数),调用start()方法

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

        int n = 100;
        for(int i=0;i<n;i++){
            System.out.println("This is main Thread " + i);
        }

    }

优点:避免单继承局限性,同一个对象可以被多个线程使用

多个线程同时去取糖果

public class D10 implements Runnable{
    private int candyNum = 50;

    @Override
    public void run() {
        while (candyNum >= 0) {
            System.out.println(Thread.currentThread().getName() + " got candy " + candyNum--);
        }
    }

    public static void main(String[] args) {
        D10 d10 = new D10();

        new Thread(d10).start();
        new Thread(d10).start();
        new Thread(d10).start();
        new Thread(d10).start();
    }
}

线程并发可能会导致资源分配出问题,比如两个线程都取了同一个资源,并且都认为只有自己获得了该资源

2.用多线程完成龟兔赛跑代码

public class Race implements Runnable{
    private static String winner;
    @Override
    public void run() {
        for(int i=0;i<=100;i++){
            if(gameOver(i)) return;
            System.out.println(Thread.currentThread().getName() + " run " + i + " miles");
        }

    }

    public boolean gameOver(int i){
        if(winner!=null) {
            return true;
        }else if(i>=100){
            winner = Thread.currentThread().getName();
            System.out.println("winner is "+ winner);
            return true;
        }else{
            return false;
        }
    }

    public static void main(String[] args) {
        Race r = new Race();
        new Thread(r, "rabbit").start();
        new Thread(r,"tortoise").start();
    }
}

 从中领会到线程是独立存在的,由CPU调度交替运行,但都有属于线程的局部变量,工作环境

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值