Java多线程Thread的创建

       Java中线程的创建有两种方式:

1.  通过继承Thread类,重写Thread的run()方法,将线程运行的逻辑放在其中

2.  通过实现Runnable接口,实例化Thread类

第一种方式:继承Thread类

package com.yyx.thread;
/**
 * 通过继承Thread类创建线程
 * yyx 2018年2月4日
 */
public class CreateThreadByextends {
    public static void main(String[] args) {
        ExtendThread extendThread = new ExtendThread();
        extendThread.setName("线程一");//设置线程名称
        extendThread.start();
        for (int i = 1; i <= 100; i++) {
            System.out.println(Thread.currentThread().getName() + ":" + i);
        }
    }
}

class ExtendThread extends Thread {

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

}

第二种方式:实现Runnable接口

package com.yyx.thread;
/**
 * 推荐:通过实现Runnable接口创建线程
 * yyx 2018年2月4日
 */
public class CreateThreadByInterface {
    public static void main(String[] args) {
        SubThread subThread=new SubThread();
        Thread thread=new Thread(subThread, "线程一");        
        thread.start();//一个线程只能够执行一次start()
        for(int i = 1;i <= 100;i++){
            System.out.println(Thread.currentThread().getName() +":" + i);
        }
    }
}

class SubThread implements Runnable {

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

}

 第三种方式:使用Calable和Future创建具备返回值的线程

package com.yyx.thread;

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

/**
 * 使用Calable和Future创建具备返回值的线程 yyx 2018年2月6日
 */
public class CreateThreadByCallable implements Callable<Integer> {
    public static void main(String[] args) {
        CreateThreadByCallable createThreadByCallable=new CreateThreadByCallable();
        FutureTask<Integer> task=new FutureTask<Integer>(createThreadByCallable);
        new Thread(task,"有返回值的线程").start();
        try {
            System.out.println(task.get());
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Integer call() throws Exception {
        Integer total=0;
        for(int i=1;i<=50;i++){
            total+=i;
        }
        return total;
    }
}

猜你喜欢

转载自www.cnblogs.com/xianya/p/9192909.html