Java中的多线程

多线程是一种Java特性,允许并发执行程序的两个或多个部分,以最大限度地利用CPU。这种程序的每一部分都称为线程。因此,线程是进程中的轻量级进程。

null

可以使用两种机制创建线程:

  1. 扩展线程类
  2. 实现可运行接口

通过扩展Thread类创建线程 我们创建一个类来扩展 JAVA线 班此类重写Thread类中可用的run()方法。线程在run()方法中开始其生命。我们为新类创建一个对象,并调用start()方法来启动线程的执行。Start()调用线程对象上的run()方法。

JAVA

// 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();
}
}
}


输出

Thread 15 is runningThread 14 is runningThread 16 is runningThread 12 is runningThread 11 is runningThread 13 is runningThread 18 is runningThread 17 is running

通过实现Runnable接口创建线程 我们创建了一个实现java的新类。lang.Runnable接口并重写run()方法。然后我们实例化一个线程对象,并对该对象调用start()方法。

JAVA

// 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();
}
}
}


输出

Thread 13 is runningThread 11 is runningThread 12 is runningThread 15 is runningThread 14 is runningThread 18 is runningThread 17 is runningThread 16 is running

线程类与可运行接口

  1. 如果我们扩展Thread类,我们的类就不能扩展任何其他类,因为Java不支持多重继承。但是,如果我们实现Runnable接口,我们的类仍然可以扩展其他基类。
  2. 我们可以通过扩展thread类来实现线程的基本功能,因为它提供了一些内置方法,如yield()、interrupt()等,这些方法在Runnable接口中不可用。
  3. 使用runnable将为您提供一个可以在多个线程之间共享的对象。

本文由 梅哈克·纳朗 。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请发表评论

© 版权声明
THE END
喜欢就支持一下吧
点赞12 分享