创建线程的三种方式(包括例子和源码解释)

本文介绍了Java中创建线程的三种方式:继承Thread类、实现Runnable接口和实现Callable接口。详细阐述每种方式的步骤、特点及应用场景,并通过源码分析比较它们的区别。例如,实现Runnable接口适合多个线程共享同一资源,Callable接口能返回计算结果并可抛出异常。
摘要由CSDN通过智能技术生成

一般来说创建线程的方法有三种,分别是:

1.继承Thread类来创建一个线程

第一步:定义一个类继承Thread类,并实现run()方法,run()方法中的内容即为线程需要完成的功能

class MyThread extends Thread{
	String name;
	public MyThread(String name) {
		this.name = name;
		System.out.println("继承Thread类");
	}
	@Override
	public void run() {
		for(int i = 1; i < 50; i++) {
			System.out.println(this.name + ":" + i);
		}
	}
}

第二步:构建子类对象,并调用对象的start()方法启动线程

public class createThread {
	
	public static void main(String[] args) {

		//创建子类的对象
		MyThread thread1 = new MyThread("one");
		MyThread thread2 = new MyThread("two");
                //启动线程
		thread1.start();
		thread2.start();
	}
}


2.实现Runnable接口来创建一个线程

第一步:定义一个类实现Runnable接口,并实现接口中的run()方法

class MyThread2 implements Runnable{
	@Override
	public void run() {
//		System.out.println("this"+this);
//		System.out.println("Thread" + Thread.currentThread());
		for(int i = 0; i < 50; i++) {
			System.out.println(Thread.currentThread().getName()+":"+i);
		}
	}	
}

第二步:创建该类对象,再创建一个Thread类对象,并把实现Runnable接口的类的对象作为参数传给Thread类对象,并调用start()方法

public class createThread {
	
	public static void main(String[] args) {
		//创建Runnable类对象
		MyThread2 t1 = new MyThread2();
		MyThread2 t2 = new MyThread2();
		//把对象作为实参传递给Thread类
		Thread thread3 = new Thread(t1,"three");
		Thread thread4 = new Thread(t2,"four");
		thread3.start();
		thread4.start();
	}
	

注意:创建的Runnable实现类只是一个target,不是线程对象,它用来指明线程运行时需要做的任务,Thread类的对象才是线程对象。

实现Runnable接口来创建一个类的好处:

  1. 一个Runnable实现类可以传给多个线程对象,所以适合多个相同程序代码的线程去处理同一个资源的情况,把线程和代码、数据有效的分离。
  2. Thread类创建线程是采用继承的方式,而Java中只能单继承。如果某个类的子类需要创建线程,那么就只能采用实现Runnable接口或者实现Callable接口的方式。


3.实现Callable接口来创建一个线程 

先定义一个Callable的实现类,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值