0
点赞
收藏
分享

微信扫一扫

Java创建线程的两种方式

phpworkerman 2022-03-12 阅读 97

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 条评论