创建线程的方法

本文详细介绍了Java中创建线程的三种方式:Thread、Runnable和Callable。通过示例代码展示了每种方式的使用方法,包括线程的启动和任务执行。Callable接口与Thread和Runnable不同,其call()方法可以返回一个值。
摘要由CSDN通过智能技术生成

创建线程的方法

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<Object> {

	@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<Object> futureTask = new FutureTask<>(callableImpl);
		Thread thread = new Thread(futureTask);
		thread.start();
		
		Object string = futureTask.get();
		System.out.println(string);
		
		//System.out.println(thread.getName());
		

	}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值