栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

创建线程的方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

创建线程的方法

创建线程的方法 1、Thread

思路:

1、创建一个类去继承thread接口,并重写run()方法。

2、在测试类中创建线程对象,调用方法start()开启线程。

示例代码:

public class MyThread extends Thread {

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

}
public class TestOfMyThread {

	public static void main(String[] args) {
		// 测试线程
		
		System.out.println(Thread.currentThread().getName());
		MyThread myThread= new MyThread();
		myThread.start();
		
		for(int i = 0;i<=100;i++) {
			System.out.println("---->"+Thread.currentThread().getName() + "  : "+i);
		}
		
		System.out.println("程序运行结束!");

	}

}
2、Runnable

思路:

1、创建一个类去实现Runnable接口,重写run() 方法。

2、在测试类中创建Runnable对象,并创建线程对象,调用start() 方法开启线程。

示例代码:

public class RunnableImpl implements Runnable {

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

}
public class TestOfRunnable {

	public static void main(String[] args) {
		System.out.println("这是创建线程的第二种方法!");
		RunnableImpl impl= new RunnableImpl();
		Thread thread = new Thread(impl);
		thread.start();
		
		for(int i = 0;i<=10;i++) {
			System.out.println("------->"+Thread.currentThread().getName()+"  : "+i);
		}
		
	}

}
3、Callable

思路:

1、创建一个类去实现Callable接口,实现call()方法。

2、在测试类中创建实现接口Callable的对象

3、创建FutrueTask对象并传入2的对象

4、创建线程对象,传入3的对象

5、调用start()方法。

注意:

run()方法是没有返回值,call方法能够返回一个值。

示例代码:

import java.util.concurrent.Callable;

public class CallableImpl implements Callable {

	@Override
	public Object call() throws Exception {
		int result = 0;
		for (int i = 0; i <= 100; i++) {
			result = result + i;
		}
		return result;
	}

}
 
import java.util.concurrent.FutureTask;

public class TestOfCallable {

	public static void main(String[] args) throws Exception, Exception {
		CallableImpl callableImpl = new CallableImpl();
		FutureTask futureTask = new FutureTask<>(callableImpl);
		Thread thread = new Thread(futureTask);
		thread.start();
		
		Object string = futureTask.get();
		System.out.println(string);
		
		//System.out.println(thread.getName());
		

	}

}


转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号