实现runnable接口

实现runnable接口

package test1;

public class TestThread3 implements Runnable {
    //主线程,main线程
    public static void main(String[] args) {
        //创建一个runnable实现接口对象
        TestThread3 testThread3=new TestThread3();
        //创建线程对象,调用start()
        new Thread(testThread3).start();

        for (int i = 0; i < 10; i++) {
            System.out.println("main线程学习"+i);
        }
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            System.out.println("run线程学习"+i);
        }
    }
}

例子:

package test1;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

//实现多线程下载图片
public class TestThread4 implements Runnable{
    private String url;
    private String filename;

    public TestThread4(String url,String filename){
        this.url=url;
        this.filename=filename;
    }

    @Override
    public void run() {
        WDownloader wDownloader=new WDownloader();
        wDownloader.downloader(url,filename);
        System.out.println("图片下载结束名字为"+filename);
    }



    public static void main(String[] args) {
        TestThread4 t1=new TestThread4("https://msdn.itellyou.cn/images/itellyou.cn.png","11.jpg");
        TestThread4 t2=new TestThread4("https://msdn.itellyou.cn/images/20200323140428-min.png","22.jpg");
        TestThread4 t3=new TestThread4("https://www.kuangstudy.com/assert/images/index_topleft_logo.png","33.jpg");

        new Thread(t1).start();
        new Thread(t2).start();
        new Thread(t3).start();

    }
}

//下载器
class WDownloader{
    //下载方法
    public void  downloader(String url,String filename){
        try {
            FileUtils.copyURLToFile(new URL(url),new File(filename));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("io异常");
        }
    }
}

此方法避免了单继承的局限性,方便同一个对象被多个线程使用

例子:

以下例子存在并发的问题

package test1;

//多个线程同时操作同一个对象
//买火车票的例子

//发现问题:多个线程操作同一个资源的情况下,线程不安全,数据紊乱
public class TestThread5 implements Runnable {

    //票数
    private int ticketNums=10;


    @Override
    public void run() {

        while(true){
            if(ticketNums<=0){
                break;
            }
            System.out.println(Thread.currentThread().getName()+"-->拿到了第"+ticketNums--+"张票");
            //Thread.currentThread().getName()获取当前线程的名字
        }
    }

    public static void main(String[] args) {

        TestThread5 t=new TestThread5();

        new Thread(t,"小明").start();
        new Thread(t,"老师").start();
        new Thread(t,"黄牛").start();
    }
}

posted @ 2021-07-08 09:22  卡卡发  阅读(89)  评论(0)    收藏  举报