线程实现的三种方式

线程实现的三种方式

方式一,继承Thread类:

package com.yonyou.sci.gateway;

/**
 * Created by Administrator on 2019/8/15.
 */
public class SubThread extends Thread{

    // 更改线程名字方法一
//    public SubThread () {
//        super("Thread 1");
//    }

    @Override
    public void run () {
        // 更改线程名字方法二
//        setName("Thread 2"); 

        for (int i = 0;i < 3; i++) {
            System.out.println(getName()+"_"+i);
        }
    }

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

}

方式二,实现Runnable接口:

package com.yonyou.sci.gateway;

/**
 * Created by Administrator on 2019/8/16.
 */
public class SubRunnable implements Runnable{

    @Override
    public void run () {
        for (int i = 0; i < 3; i++) {
            System.out.println(Thread.currentThread().getName()+"_"+i);
        }
    }

    public static void main(String[] args) {
        SubRunnable sr = new SubRunnable();
        Thread t = new Thread(sr);
        // 更改线程名字
        t.setName("123");
        
        t.start();
    }

}

方式三、实现Callable<String>接口:

备注:a.此接口特点是有返回值; b.能抛出异常。

package com.yonyou.sci.gateway;

import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;

public class SubCallable implements Callable<String> {

    @Override
    public String call () {
        return "call";
    }

    public static void main(String[] args) throws Exception{
        SubCallable sc = new SubCallable();
        FutureTask<String> ft = new FutureTask<String>(sc);
        Thread t = new Thread(ft);
        t.start();
        String s = ft.get();
        System.out.println(s);
    }

}

 

posted @ 2019-10-22 23:40  唐胜伟  阅读(264)  评论(0编辑  收藏  举报