How to use threads in Java programming

Source: Internet
Author: User
Tags thread class

The Java platform is designed to be a multithreaded environment from the outset. When your main program executes, other tasks such as fragmentation collection and event handling are done in the background. Essentially, you can think of these jobs as threads. They happen to be system-managed threads, but they are threads anyway. Threads allow you to define separate jobs that do not interfere with each other. The system will swap these jobs into or out of the CPU so that (from the outside) they appear to be running at the same time.

You can also use multiple processes when you need to work with multiple jobs in your program. These processes can be created by yourself, and you can manipulate system threads.

You do these multiple job processing, using several different classes or interfaces:

Java.util.Timer class

Javax.swing.Timer class

Thread class

Runnable interface

For a simple job, which usually needs to be repeated, you can use the Java.util.Timer class to tell it to "do it every half second." Note: Most system routines are used in milliseconds. Half a second is 500 milliseconds.

The task you want the timer to implement is defined in the Java.util.TimerTask instance, where the method that is run contains the task to be performed. These are shown in the Hi class where the string "Hi" is repeatedly displayed on the screen until you press ENTER.

import java.util.*;
public class Hi {
public static void main(String args[])
throws java.io.IOException {
TimerTask task = new TimerTask() {
public void run() {
System.out.println("Hi");
}
};
Timer timer = new Timer();
timer.schedule(task, 0, 500);
System.out.println("Press ENTER to stop");
System.in.read(new byte[10]);
timer.cancel();
}
}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.