Java Threads: The Basics

Method 1: Write a class that implements the Runnable interface (i) Put the thread code in the run() method. (ii) Create a thread object by passing a Runnable object as an argument to the Thread constructor. The Thread object now has a Runnable object that implements the run() method. Like this: (new Thread(new MyThread())).start(); Simple code sample as follows: [code language="java"] package javathread1; class MyThread implements Runnable { public void run() { //Display info about thread System.out.println(Thread.currentThread()); } } public class JavaThread1 { public static void main(String[] args) { // Create the thread Thread thread1 = new Thread(new MyThread(), "thread 1"); // Start the thread thread1.start(); } } [/code] Method 2: Declare the class to be a Subclass of the Thread class (i) Override the run() method from the Thread class to define the code executed by the thread. (ii) Invoke the start() method inherited from the Thread class to make the thread eligible for running. Code sample as follows: [code language="java"] package javathread1; class MyThread extends Thread { public void run() { //Display info about this particular thread System.out.println(Thread.currentThread().getName()); } } public class JavaThread1 { public static void main(String[] args) { Thread thread1 = new MyThread(); thread1.start(); } } [/code]

Comments

Popular posts from this blog

Using the Supervisor Controller Pattern to access View controls in MVVM

Getting started with client-server applications in C++

How to send an e-mail via Google SMTP using C#