-2
我想知道如何通过“扩展线程类”创建多个线程。我知道它是如何使用“Runnable”完成的。请告诉我如何通过“扩展线程类”来完成。通过扩展线程类创建多个线程
我想知道如何通过“扩展线程类”创建多个线程。我知道它是如何使用“Runnable”完成的。请告诉我如何通过“扩展线程类”来完成。通过扩展线程类创建多个线程
主要方法
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();
}
}
这个类是通过扩展 “主题” 类做成一个线程。
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完整的细节,对于快速阅读我米距离上述基准
你为什么不告诉我们你已经尝试什么,然后我们可以帮你发布的代码。 –
我是java的初学者。我不知道它是如何完成的。我在开始时出现问题 – Aadithya
您可以在这里找到:http://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html –