Working with Threads

How Tomcat Works

A Guide to Developing Your Own Java Servlet  Container

Catalina uses many threads to handle different things. This chapter's application assigns a separate thread for handling requests. Therefore, you need to understand how to work with threads in Java, as described in this section.

There are a number of ways to create a new thread of execution. One is to declare a class to be a subclass of java.lang.Thread. This subclass should override the run method of class Thread. An instance of the subclass can then be allocated and started. For example, consider the test.ThreadDemo class in Listing 3.1.

Listing 3.1: The ThreadDemo Class

package test;

public class ThreadDemo extends Thread {

  public void run() {

    int counter = 0;

    while (counter < 5) {

      System.out.println("running " + counter);

      counter++;

    }

  }

  public static void main(String[] args) {

    ThreadDemo demo = new ThreadDemo();

    demo.start();

  }

}

The ThreadDemo class extends java.lang.Thread and overrides the Thread class’s run method. The run method is executed when the Thread is started by calling its start method. In the ThreadDemo class, the main method creates a Thread and starts it, which results in the run method being executed. When the ThreadDemo class is run, the following output is displayed in the console.

running 0running 1running 2running 3running 4

The ThreadDemo class uses inheritance. However, if you are only interested in overriding the run method of the Thread, you are better off implementing the java.lang.Runnable interface and providing the implementation of the interface’s run method, and this is the second way to create a thread. An instance of your class can then be allocated, passed as an argument when creating Thread, and started. The test.RunnableDemo class in Listing 3.2 does the same thing as the ThreadDemo class. 

Listing 3.2: The RunnableDemo Class

package test;

public class RunnableDemo implements Runnable {

  public void run() {

    int counter = 0;

    while (counter < 5) {

      System.out.println("running " + counter);

      counter++;

    }

  }

  public void start() {

    Thread thread = new Thread(this);

    thread.start();

  }

  

  public static void main(String[] args) {

    RunnableDemo demo = new RunnableDemo();

    demo.start();

  }

The technique used to create a thread by implementing the Runnable interface is used for the ex03.pyrmont.connector.http.HttpConnector class, as you will see later in this chapter.

转载于:https://my.oschina.net/zhongwenhao/blog/149624

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值