top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to create thread in java ?

+1 vote
392 views

Give some example code for using thread in java?

posted Jul 22, 2014 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

Threads are objects like any other Java objects and are instances of class java.lang.thread, or instances of subclasses of this class. Java threads can also execute code which was not possible with normal objects -

Creating a thread in Java is done like this:

  Thread thread = new Thread();

To start the thread you will call its start() method, like this:

  thread.start();

Example

Thread thread = new Thread(){
    public void run(){
      System.out.println("I am inside the thread");
    }
  }

  thread.start();
answer Jul 23, 2014 by Salil Agrawal
if you want your thread to return some value You can use the callable interface in java.util.concurrent package

Sample code :
public class CallableThreadDemo implements Callable<String> {

    @Override
    public String call() throws Exception {
       
        return "callable running with name : "+Thread.currentThread().getName();
    }
   
   
    public static void main(String[] args) throws Exception {
        CallableThreadDemo thread = new CallableThreadDemo();
        CallableThreadDemo thread2 = new CallableThreadDemo();
        ExecutorService exec = Executors.newFixedThreadPool(2);
       
        Future<String> future1 = exec.submit(thread);
        Future<String> future2 = exec.submit(thread2);
        exec.awaitTermination(100, TimeUnit.MILLISECONDS);
        System.out.println(future1.get());
        System.out.println(future2.get());
        exec.shutdown();
    }
}
...