Java创建线程的两种方式

Java创建线程的两种方式:

1.继承Thread类

// Java code for thread creation by extending
// the Thread class
class MultithreadingDemo extends Thread {
	public void run()
	{
		try {
			// Displaying the thread that is running
			System.out.println(
				"Thread " + Thread.currentThread().getId()
				+ " is running");
		}
		catch (Exception e) {
			// Throwing an exception
			System.out.println("Exception is caught");
		}
	}
}

// Main Class
public class Multithread {
	public static void main(String[] args)
	{
		int n = 8; // Number of threads
		for (int i = 0; i < n; i++) {
			MultithreadingDemo object
				= new MultithreadingDemo();
			object.start();
		}
	}
}

输出:

线程 13 正在运行
线程 11 正在运行
线程 12 正在运行
线程 15 正在运行
线程 14 正在运行
线程 18 正在运行
线程 17 正在运行
线程 16 正在运行

我们创建新类的对象并调用 start() 方法来开始执行线程。Start() 调用 Thread 对象的 run() 方法。继承之后的thread可以重写父类Thread中的Run方法,只有当线程的run方法执行时,才算真正开始线程的生命周期。

2.实现Runnable接口

// Java code for thread creation by implementing
// the Runnable Interface
class MultithreadingDemo implements Runnable {
	public void run()
	{
		try {
			// Displaying the thread that is running
			System.out.println(
				"Thread " + Thread.currentThread().getId()
				+ " is running");
		}
		catch (Exception e) {
			// Throwing an exception
			System.out.println("Exception is caught");
		}
	}
}

// Main Class
class Multithread {
	public static void main(String[] args)
	{
		int n = 8; // Number of threads
		for (int i = 0; i < n; i++) {
			Thread object
				= new Thread(new MultithreadingDemo());
			object.start();
		}
	}
}

创建一个实现 java.lang.Runnable 接口并覆盖 run() 方法的新类。然后我们实例化一个 Thread 对象并在这个对象上调用 start() 方法。 

输出:

线程 13 正在运行
线程 11 正在运行
线程 12 正在运行
线程 15 正在运行
线程 14 正在运行
线程 18 正在运行
线程 17 正在运行
线程 16 正在运行

总结:

1:继承Thread类之后,由于 Java单继承的特点,当前的类就不能继承其他的类。但是实现Runnable接口,就可以继承其他类。

2:继承Thread类,使得当前类拥有一些内置方法:yiled(),interrupt() 等。

3:使用 runnable 将为您提供一个可以在多个线程之间共享的对象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值