码迷,mamicode.com
首页 > 编程语言 > 详细

Java多线程Thread的创建

时间:2018-06-17 16:01:51      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:tar   print   trace   +=   oid   返回值   java   string   继承   

       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;
    }
}

 

Java多线程Thread的创建

标签:tar   print   trace   +=   oid   返回值   java   string   继承   

原文地址:https://www.cnblogs.com/xianya/p/9192909.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!