Java创建线程的三种方式

Java中创建线程主要有三种方式:
一、继承Thread类
1、继承Thread,重写run方法。
2、创建Thread子类的实例,创建线程对象。
3、调用start()方法启动线程。

package com.test;

public class FirstThread extends Thread{

    public void run(){
        for (int i = 0; i < 20; i++) {
            System.out.println(this.getName()+"--"+i);
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            System.out.println(Thread.currentThread().getName()+"--"+i);
            if(i==10){
                new FirstThread().start();
                new FirstThread().start();
            }
        }
    }
}

二、通过Runnable接口创建线程
1、实现runnable接口,重写run()方法。
2、创建 Runnable实现类的实例,依此实例作为Thread的target来创建Thread对象,该Thread对象才是真正的线程对象。
3、调用start()方法启动线程。

package com.test;

public class SecondThread implements Runnable{

    public void run() {
        for(int i=0;i<20;i++){
            System.out.println(Thread.currentThread().getName()+"--"+i);
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 20; i++) {
            System.out.println(Thread.currentThread().getName()+"--"+i);
            if(i==10){
                SecondThread st=new SecondThread();
                new Thread(st,"线程1").start();
                new Thread(st,"线程2").start();
            }
        }
    }
}

三、通过Callable和Future创建线程
1、实现Callable接口,实现call()方法,该call()方法将作为线程执行体,并且有返回值。
2、创建Callable实例,使用FutureTask包装Callable对象,FutureTask对象封装了Callable对象的call()方法的返回值。
3、FutureTask对象作为Thread对象的target创建并启动新线程。
4、调用FutureTask对象的get()方法来获得子线程执行结束后的返回值。

package com.test;

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

public class CallableThread implements Callable<Integer> {

    public Integer call() throws Exception {
        int i = 0;  
        for(i=0;i<20;i++){  
            System.out.println(Thread.currentThread().getName()+" "+i);  
        }  
        return i;  
    }

    public static void main(String[] args) {
        CallableThread ct = new CallableThread();  
        FutureTask<Integer> ft = new FutureTask<Integer>(ct);  
        for(int i = 0;i < 20;i++)  {  
            System.out.println(Thread.currentThread().getName()+" "+i);  
            if(i==10){  
                new Thread(ft,"返回值的线程").start();  
            }  
        } 
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值