Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 1

Threads are very important to the Java world and to many other languages.

Java is capable of running more than one thread at a time, which is very useful, but can cause confusion if misused. As a specific example of the utility of threads, suppose you are designing an interface that accepts keyboard and mouse input from the user. Without the use of threads, if the user were to input from both keyboard and mouse simultaneously, the interface would be forced to process those inputs sequentially, which would likely be perceptible to the user. But by using threads, the inputs could be processed in a way that appears simultaneous to the user. There are two ways you can create threads. The first is to extend the Thread class itself. The second is by implementing the Runnable interface. Generally, it is best to implement Runnable unless you have a specific reason not to (e.g. overriding methods other than run()).
public class Calendar extends Thread { public void run() { //code here } } public class SomeOtherClass { public static void main() { Calendar theCalendar = new Calendar(); theCalendar().start(); } } public class Calendar implements Runnable { public void run() { //code here } } public class SomeOtherClass { public static void main() { Thread theCalendar = new Thread(new Calendar()); theCalendar().start(); } }

You might also like