2013-10-02 4 views
-2

Я хочу знать, как несколько потоков могут быть созданы путем расширения класса Thread. Я знаю, как это делается с помощью «Runnable». Скажите, пожалуйста, как это можно сделать, «расширяя класс Thread».Создание нескольких потоков путем расширения класса потоков

+0

Почему не вы показать нам, что вы пробовали, и тогда мы можем помочь вам. –

+0

Я новичок в java. Я не знаю, как это сделано. У меня возникли проблемы с запуском – Aadithya

+1

Здесь вы найдете: http://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html –

ответ

7

Главная Метод

public class ThreadDemo 
{ 

    public static void main(String args[])  
    {   

    //Creating an object of the first thread   
    FirstThread firstThread = new FirstThread();    

    //Creating an object of the Second thread  
    SecondThread secondThread = new SecondThread();    

    //Starting the first thread   
    firstThread.start();     

    //Starting the second thread   
    secondThread.start(); 
    } 
} 

Этот класс выполнен в виде нити, расширив класс "Thread".

public class FirstThread extends Thread 
{ 
    //This method will be executed when this thread is executed 
    public void run() 
    { 

    //Looping from 1 to 10 to display numbers from 1 to 10 
    for (int i=1; i<=10; i++) 
    { 
     //Displaying the numbers from this thread 
     System.out.println("Messag from First Thread : " +i); 

     /*taking a delay of one second before displaying next number 
     * 
     * "Thread.sleep(1000);" - when this statement is executed, 
     * this thread will sleep for 1000 milliseconds (1 second) 
     * before executing the next statement. 
     * 
     * Since we are making this thread to sleep for one second, 
     * we need to handle "InterruptedException". Our thread 
     * may throw this exception if it is interrupted while it 
     * is sleeping. 
     * 
     */ 
     try 
     { 
      Thread.sleep(1000); 
     } 
     catch (InterruptedException interruptedException) 
     { 
      /*Interrupted exception will be thrown when a sleeping or waiting 
      * thread is interrupted. 
      */ 
      System.out.println( "First Thread is interrupted when it is sleeping" +interruptedException); 
     } 
     } 
    } 

Этот класс выполнен в виде нити, расширяя класс "темы".

public class SecondThread extends Thread 
{ 

    //This method will be executed when this thread is executed 
    public void run()  
    {    
    //Looping from 1 to 10 to display numbers from 1 to 10  
    for (int i=1; i<=10; i++)   
    {   
     System.out.println("Messag from Second Thread : " +i);      
     /*taking a delay of one second before displaying next number 
     * "Thread.sleep(1000);" - when this statement is executed, 
     * this thread will sleep for 1000 milliseconds (1 second) 
     * before executing the next statement.    
     *    
     * Since we are making this thread to sleep for one second, 
     * we need to handle "InterruptedException". Our thread 
     * may throw this exception if it is interrupted while it 
     * is sleeping.    
     */   
     try   
     {     
      Thread.sleep (1000);   
     }    
     catch (InterruptedException interruptedException)    
     {     
      /*Interrupted exception will be thrown when a sleeping or waiting 
      *thread is interrupted.    
      */    
      System.out.println("Second Thread is interrupted when it is sleeping" +interruptedException);   
     }   
    } 
    } 
} 

Пожалуйста, проверьте ссылки # Threading using Extend для полной детализации, для быстрого чтения я м проводки код из указанной выше ссылке

Смежные вопросы