Java创建线程的三种方式

1. 继承Thread 

1.1创建类并且继承Thread类,重写 run() 方法。

package cn.zzw;

public class FirstThread extends Thread
{
    @Override
    public void run()
    {
        for (int i = 0; i < 10; i++)
        {
            try
            {
                Thread.sleep(2000);
                System.out.println("zzw,i="+i);
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }
}

1.2 调用start() 方法来启动线程。

public class ThreadDemo
{
    public static void main(String[] args)
    {
        new FirstThread().start();
    }
}

 1.3 结果:

 

2. 实现Runnable接口创建线程类

2.1 定义runnable接口的实现类,并重写该接口的run()方法

package cn.zzw;

public class SecondRunnable implements Runnable
{
    @Override
    public void run()
    {
        for (int i = 0; i < 10; i++)
        {
            try
            {
                Thread.sleep(2000);
                System.out.println("SecondRunnable: i="+i);
            } catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
    }
}

2.2 调用线程对象的start()方法来启动该线程。

package cn.zzw;

public class ThreadDemo
{
    public static void main(String[] args)
    {
        Runnable runnable = new SecondRunnable();
        new Thread(runnable).start();
    }
}

2.3 结果:

 

 

3. 通过Callable和Future创建线程

3.1 创建Callable接口的实现类,并实现call()方法,该方法有返回值

package cn.zzw;

import java.util.concurrent.Callable;

public class ThirdCallable implements Callable<Integer>
{
    @Override
    public Integer call() throws Exception
    {
        //TODO
        return 100;
    }
}

3.2 使用FutureTask类来包装Callable对象,该FutureTask对象封装了该Callable对象的call()方法的返回值。

3.3 使用FutureTask对象作为Thread对象的target创建并启动新线程。

3.4 使用FutureTask对象的get()方法来获得子线程执行结束后的返回值。

package cn.zzw;

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

public class ThreadDemo
{
    public static void main(String[] args)
    {
        Callable callable=new ThirdCallable();
        FutureTask<Integer> ft = new FutureTask<>(callable);
        new Thread(ft).start();
        try
        {
            Integer result = ft.get();
            System.out.println("Result: result="+result);
        } catch (InterruptedException e)
        {
            e.printStackTrace();
        } catch (ExecutionException e)
        {
            e.printStackTrace();
        }
    }
}

3.5 结果:

 

 

4.三种方式的比较:

实现Runnable接口和实现Callabled接口的调用方式相同,实现Callable执行的call 方法有返回值。这两种方法还可以继承其他类。而采用继承Thread的方式,不能再继承其他父类,编写方法也比较简单。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值