成都创新互联网站制作重庆分公司

java中怎样创建线程

今天就跟大家聊聊有关java中怎样创建线程,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

在山西等地区,都构建了全面的区域性战略布局,加强发展的系统性、市场前瞻性、产品创新能力,以专注、极致的服务理念,为客户提供做网站、成都网站设计 网站设计制作定制网站建设,公司网站建设,企业网站建设,品牌网站建设,成都全网营销,成都外贸网站建设公司,山西网站建设费用合理。

1.  继承Thread类
2.  实现Runnable接口
3.  实现Callable接口,使用FutureTask方式
4.  使用线程池

 1. 继承Thread类

package com.pimee.thread;
/**
 * 继承Thread创建线程
 * @author Bruce Shaw
 *
 */
public class ThreadTest extends Thread {

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

	@Override
	public void run() {
		System.out.println("This is TestThread...");
	}
}

2. 实现Runnable接口

package com.pimee.thread;
/**
 * 实现runnable接口创建线程
 * @author Bruce Shaw
 *
 */
public class RunnableTest implements Runnable {
	private static int test = 10;

	@Override
	public void run() {
		System.out.println("This is RunnableTest...");
	}

	public static void main(String[] args) {
		RunnableTest test = new RunnableTest();
		new Thread(test).start();
	}
}

以上两种方式实现都比较简单,缺点很明显,就是线程执行后没有返回值。且看下面带有返回值的实现方式:

3. 实现Callable接口,使用FutureTask方式

package com.pimee.thread;

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

/**
 * 实现callable接口,基于FutureTask方式实现
 * @author Bruce Shaw
 *
 */
public class CallableTest implements Callable {

	public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
		CallableTest mc = new CallableTest();
		FutureTask ft = new FutureTask<>(mc);
		Thread thread = new Thread(ft);
		thread.start();
		System.out.println(ft.get());
	}

	@Override
	public String call() throws Exception {
		System.out.println("Callable is running...");
		return "Callable finished and return value...";
	}
}

4. 使用线程池

package com.pimee.thread;

import java.util.concurrent.*;
/**
 * 基於线程池创建
 *
 * @author Bruce Shaw
 *
 */
public class ThreadPoolTest implements Callable {

    public static void main(String[] args) throws InterruptedException, ExecutionException, TimeoutException {
        ExecutorService newCachedThreadPool = Executors.newSingleThreadExecutor();
        Future future = newCachedThreadPool.submit(new CallableTest());
        try {
            System.out.println(future.get());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            newCachedThreadPool.shutdown();
        }
    }

    @Override
    public String call() throws Exception {
        System.out.println("Callable is running...");
        return "Callable finished and return value...";
    }
}

看完上述内容,你们对java中怎样创建线程有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注创新互联行业资讯频道,感谢大家的支持。


当前题目:java中怎样创建线程
URL网址:http://cxhlcq.com/article/jscide.html

其他资讯

在线咨询

微信咨询

电话咨询

028-86922220(工作日)

18980820575(7×24)

提交需求

返回顶部