`
standalone
  • 浏览: 614297 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Multithreading in Java (5)

    博客分类:
  • java
阅读更多

Multithreading in Java - Creating a Thread by Using extends


(Page 5 of 10 )

You can inherit the Thread class as another way to create a thread in your program. As you’ll recall from Chapter 8, you can cause your class to inherit another class by using the keyword extends when defining your class. When you declare an instance of your class, you’ll also have access to members of the Thread class.

Whenever your class inherits the Thread class, you must override the run() method, which is an entry into the new thread. The following example shows how to inherit the Thread class and how to override the run() method.

This example defines the MyThread class, which inherits the Thread class. The constructor of the MyThread class calls the constructor of the Thread class by using the super keyword and passes it the name of the new thread, which is My thread. It then calls the start() method to activate the new thread.

The start() method calls the run() method of the MyThread class. As you’ll notice in this example, the run() method is overridden by displaying two lines on the screen that indicate that the child thread started and terminated. Remember that statements within the run() method constitute the portion of the program that runs as the thread. Therefore, your program will likely have more meaningful statements within the definition of the run() method than those used in this example.

The new thread is declared within the main() method of the Demo class, which is the program class of the application . After the thread starts, two messages are displayed, indicating the status of the main thread.

class MyThread extends Thread {
  
MyThread(){
    
super("My thread");
    
start();
  
}
  
public void run() {
      System.out.println("Child thread started");
      System.out.println("Child thread terminated");
  
}
}
class Demo {
  
public static void main (String args[]){
      new MyThread();
      System.out.println("Main thread started");
      System.out.println("Main thread terminated");
  
}
}


NOTE:    As a rule of thumb, you should implement the Runnable interface if the run() method is the only method of the Thread class that you need to override. You should inherit the Thread class if you need to override other methods defined in the Thread class.

Using Multiple Threads in a Program

It is not unusual to need to run multiple instances of a thread, such as when your program prints multiple documents concurrently. Programmers call this spawning a thread. You can spawn any number of threads you need by first defining your own class that either implements the Runnable interface or inherits the Thread class and then declaring instances of the class. Each instance is a new thread.

Let’s see how this is done. The next example defines a class called MyThread that implements the Runnableinterface. The constructor of the MyThreadclass accepts one parameter, which is a string that is used as the name of the new thread. We create the new thread within the constructor by calling the constructor of the Thread class and passing it a reference to the object that is defining the thread and the name of the thread. Remember that the this keyword is a reference to the current object. The start() method is then called, which calls the run() method.

The run() method is overridden in the MyThread class. Two things happen when the run() method executes. First, the name of the thread is displayed on the screen. Second, the thread pauses for 2 seconds when the sleep() method is called. The sleep() method is defined in the Thread class can accept one or two parameters. The first parameter is the number of milliseconds the thread is to pause. The second parameter is the number of microseconds the thread pauses. In this example, we’re only interested in milliseconds, so we don’t need to include the second parameter (2,000 nanoseconds is 2 seconds). After the thread pauses, another statement is displayed on the screen stating that the thread is terminating.

The main() method of the Demo class declares four instances of the same thread by calling the constructor of the MyThread class and passing it the name of the thread. Each of these is treated as a separate thread. The main thread is then paused 10 seconds by a call to the sleep() method. During this time, the threads continue to execute. When the main thread awakens, it displays the message that the main thread is terminating.

Here’s what is displayed on the screen when this example runs:

Thread: 1
Thread: 2
Thread: 3
Thread: 4
Terminating thread: 1
Terminating thread: 2
Terminating thread: 3
Terminating thread: 4
Terminating thread: main thread.
class MyThread implements Runnable {
  String tName;
  Thread t;
  MyThread (String threadName) {
    
tName = threadName;
     t = new Thread (this, tName);
     t.start();
 
}
  public void run() {
    
try {
        System.out.println("Thread: " + tName );
        Thread.sleep(2000);
    
} catch (InterruptedException e ) {
       System.out.println("Exception: Thread "
              
+ tName + " interrupted");
     }
     System.out.println("Terminating thread: " + tName );
 
}
}
class Demo {
   
public static void main (String args []) {
      new MyThread ("1");
      new MyThread ("2");
      new MyThread ("3");
      new MyThread ("4");
      try {
        
Thread.sleep (10000);
      } catch (InterruptedException e) {
        System.out.println(
                
"Exception: Thread main interrupted.");
      }
      System.out.println(
                 
"Terminating thread: main thread.");
  }
}

分享到:
评论

相关推荐

    《Programming in Java Second Edition》高清完整英文PDF版

    Multithreading in Java Chapter 9. Input/Output, Serialization and Cloning Chapter 10. Generics, java.util and other API Chapter 11. Network Programming Chapter 12. Applets Chapter 13. Event Handling ...

    thinking in Java

    其中,"multithreading applications in Win32.pdf"可能是一个关于Windows平台下多线程应用的补充材料,可能出自另一本书或文章,但与《Thinking in Java》的主题相关。多线程是Java编程中的一个重要部分,它允许...

    1Z0-811 Exam Guide to Have a Cakewalk in Oracle Java SE Certific

    - **Concurrency:** Explore concurrency concepts and multithreading in Java. #### Conclusion The 1Z0-811 exam is a significant step towards achieving Oracle Java SE certification. By following a ...

    Multithreading-in-java

    Java多线程 多线程是Java的一项功能,它允许并发执行程序的两个或更多部分,以最大程度地利用CPU。 这种程序的每个部分都称为线程。 因此,线程是进程中的轻量级进程。 可以使用两种机制来创建线程: 扩展Thread类...

    Java: High-Performance Apps with Java 9

    In 1999, with his wife Luda and two daughters, he emigrated to the USA and has been living in Colorado ever since, working as a Java programmer. In his free time, Nick likes to write and hike in the ...

    Java-Concurrency-Multithreading-in-Practice:Packt出版的《 Java Concurrency&Multithreading in Practice》

    实践中的Java并发和多线程 这是发行的的代码存储库。 它包含从头到尾完成视频课程所需的所有支持项目文件。 关于视频课程 多核处理器无处不在-从超级计算机到随身携带的移动设备。 这就是为什么现代开发人员必须知道...

    A Textbook of Java Programming

    It also discusses about exception handling, multithreading and java libraries. Further, it explains how to interact with client side applications like applets and handling events. The last section ...

    JAVA核心技术卷一卷二(中文)之part2分卷

    Chapter 3 Fundamental Programming Structures in Java(新增批注共44条) Chapter 4 Objects and Classes(新增批注共55条) Chapter 5 Inheritance(新增批注共42条) Chapter 6 Interfaces and Inner Classes...

    Java Performance and Scalability

    This book was written with one goal in mind: to provide Java programmers with the expertise needed to build efficient, scalable Java code. The author shares his experience in server-side performance ...

    Java.to.Python 高清完整epub版

    If Java is the heavy metal of computer programming, then Python is the jazz that opens doors of freedom in software development. Both Java and Python are object-oriented programming languages. Both ...

    Modern Multithreading

    Carver和Kuo-Chung Tai撰写,由John Wiley & Sons, Inc.出版,是一本深入探讨多线程编程的专著,尤其聚焦于Java和C++(包括Pthreads和Win32)语言环境下的多线程程序设计、测试与调试。本书不仅适合初学者作为入门...

    java面试题英文版及其答案

    s built-in support for multithreading through the Thread class and the Runnable interface. By creating and starting multiple threads, a Java application can perform several operations simultaneously, ...

    Thinking_in_Java_4th_Edition_CN

    9. **多线程(Multithreading)**:Java支持多线程编程,书中会讲解线程的创建、同步和通信,以及线程池的使用。 10. **输入/输出流(I/O Stream)**:介绍如何在Java中进行文件读写,网络通信以及其他类型的输入...

    Java - A Beginner’s Guide - Sixth Edition - Herbert Schildt

    This chapter introduces multithreading concepts and techniques in Java, including thread creation, synchronization, and inter-thread communication. Multithreading is particularly useful for improving...

    Core Java. Volume I. Fundamentals, 8th Edition JAVA核心技术1基础知识

    3 FUNDAMENTAL PROGRAMMING STRUCTURES IN JAVA 4 OBJECTS AND CLASSES 5 INHERITANCE 6 INTERFACES AND INNER CLASSES 7 GRAPHICS PROGRAMMING 8 EVENT HANDLING 9 USER INTERFACE COMPONENTS WITH SWING 10 ...

    Core.Java.B013WZRDNQ

    Core Java offers a total immersion approach for CC++ programmer wanting to learn java. The course will use JDK(Java Development Kit) and covers all the ...Chapter 13 Managing Input/Output Files in Java

    producer_consumer_using_multithreading_in_java:用Java实现的经典生产者消费者问题的多线程解决方案

    6. ** 示例代码 **:在`producer_consumer_using_multithreading_in_java-master`这个项目中,应该包含了一个完整的示例,演示了如何用Java实现生产者消费者模型。源代码可能包括一个`Producer`类和一个`Consumer`类...

    JAVA核心技术卷一卷二(中文)之part4分卷

    Chapter 3 Fundamental Programming Structures in Java(新增批注共44条) Chapter 4 Objects and Classes(新增批注共55条) Chapter 5 Inheritance(新增批注共42条) Chapter 6 Interfaces and Inner Classes...

Global site tag (gtag.js) - Google Analytics