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

Multithreading in Java (4)

    博客分类:
  • java
阅读更多

 

Multithreading in Java - Creating Your Own Thread


(Page 4 of 10 )

Remember, your program is the main thread, and other portions of your program can also be a thread. You can designate a portion of your program as a thread by creating your own thread. The easiest way to do this is to implement the Runnable interface. Implementing the Runnable interface is an alternative to your class inheriting the Thread class.

An interface describes one or more method members that you must define in your own class in order to be compliant with the interface. These methods are described by their method name, argument list, and return value.

The Runnable interface describes the method classes needed to create and interact with a thread. In order to use the Runnable interface in your class, you must define the methods described by the Runnable interface.

Fortunately, only you need to define one method described by the Runnable interface—the run() method. The run() method must be a public method, and it doesn’t require an argument list or have a return value.

The content of the run() method is the portion of your program that will become the new thread. Statements outside the run() method are part of the main thread. Statements inside the run() method are part of the new thread. Both the main thread and the new thread run concurrently when you start the new thread, which you’ll learn how to do in the next example. The new thread terminates when the run() method terminates. Control then returns to the statement that called the run() method.

When you implement the Runnable interface, you’ll need to call the following constructor of the Thread class. This constructor requires two arguments. The first argument is the instance of the class that implements the Runnable interface and tells the constructor where the new thread will be executed. The second argument is the name of the new thread. Here’s the format of the constructor:

Thread (Runnable class, String name)

The constructor creates the new thread, but it does not start the thread. You explicitly start the new thread by calling the start()method. The start() method calls the run() method you defined in your program. The start() method has no argument list and does not return any values.

The following example illustrates how to create and start a new thread. Here’s what is displayed when this program runs:

Main thread started
Child thread started
Child thread terminated
Main thread terminated

NOTE:   The output of this program may be different when you run this program. Some Java run-time environments terminate the main thread before the child thread, whereas others terminate the child thread before the main thread. Therefore, the text shown here might appear in a different order when you run this program.


 

class MyThread implements Runnable{
   Thread t;
   MyThread () {
     
t = new Thread(this,"My thread");
     
t.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");
   }
}

This example begins by defining a class called MyThread, which implements the Runnable interface. Therefore, we use the keyword implements to implement the Runnable interface. Next, a reference to a thread is declared. Defining the constructor for the class follows this. The constructor calls the constructor of the Thread class. Because we are implementing the Runnable interface, we need to pass the constructor reference to the instance of the class that will execute the new thread and the name of the new thread. Notice that we use the keyword this as reference to the instance of the class. The keyword this is a reference to the current instance of the class.

The constructor returns a reference to the new thread, which is assigned to the reference declared in the first statement in the MyThread class definition. We use this reference to call the start() method. Remember that the start() method calls the run() method.

Next,we define the run() method. Statements within the run() method become the portion of the program that executes when the thread executes. There are only two displayed statements in the run() method. Later in this chapter, we’ll expand the run() method to include more interesting statements.

Next, we define the program class. The program class explicitly executes the new thread by creating an instance of the MyThread class. This is done by using the new operator and calling the constructor of MyThread.

Finally, the program finishes by displaying two lines on the screen.


分享到:
评论

相关推荐

    《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 ...

    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 ...

    Multithreading-in-java

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

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

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

    Thinking_in_Java_4th_Edition_CN

    《Thinking in Java 4th Edition CN》中文版是Java编程领域的经典著作,由Bruce Eckel撰写,对中国程序员来说是一份非常宝贵的资源。这本书全面而深入地介绍了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, ...

    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 ...

    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...

    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.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`类...

Global site tag (gtag.js) - Google Analytics