[Java]Three ways to implements Thread

[Java]Three ways to implements Thread

1. extends Class Thread

  • define Myclass that extends Thread
  • override Run()
  • new object to call start() to start thread. If call run() directly, it can’t be implemented concurrently, will be called by order. Start() will call run method concurrently.

public void start()
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread. The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.

//example, create three threads to download pic from specificate URL concurrly
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;

import java.net.URL;

public class PictureDownloader extends Thread{
    private String url;
    private String name;

    public PictureDownloader(String url, String name) {
        this.url = url;
        this.name = name;
    }

    @Override
    public void run() {
        try {
            new Downloader().picDownloader(url,name);
            System.out.println("download "+ name + "finished!\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] avrg){
        PictureDownloader t1 = new PictureDownloader("https://img-blog.csdn.net/xx","1");
        PictureDownloader t2 = new PictureDownloader("https://img-home.csdnimg.cn/images/xx4.gif","2");
        PictureDownloader t3 = new PictureDownloader("https://avatar.csdnimg.cn/2/4/4/3xx.jpg","3");
        //start
        t1.start();
        t2.start();
        t3.start();

    }
}

class Downloader {
    public void picDownloader(String url, String name) throws IOException {
        FileUtils.copyURLToFile(new URL(url),new File(name));
    }
}


note: Class Thread is provided by jdk as core function in rt.jar java.lang package
details: https://docs.oracle.com/javase/8/docs/api/index.html

2. implements Runnable interface (recommendation)

  • define Myclass implements Runnable interface
  • override run() method
  • new object of Myclass, take the object as parameter to new Thread and call start() methon. Thread plays as static agent.
//example, The Tortoise and the Hare
public class Race implements Runnable{

    private static String winner;
    @Override
    public void run() {

        for (int i = 0; i <=100; i++) {
            boolean flag = gameOver(i);
            if(flag){
                break;
            }
            if(Thread.currentThread().getName() == "兔子" && i%10 == 0){
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            System.out.println(Thread.currentThread().getName() + "跑了第" + i + "步\n");

        }

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

    }
    public static void main(String[] avrg){
        Race race = new Race();
        new Thread(race,"兔子").start();
        new Thread(race,"乌龟").start();
    }
}

3. implements Callable interface

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值