本文详细介绍Java多线程程序设计入门
通过Runnable接口,在该接口中定义run()方法的接口。所谓接口跟类非常类似,主要用来实现特殊功能,如复杂关系的多重继承功能。在此,我们定义一个实现Runnable() 接口的类,在该类中定义自己的run()方法,然后以该类的实例对象为参数调用Thread类的构造方法来创建一个线程。
线程被实际创建后处于待命状态,激活(启动)线程就是启动线程的run()方法,这是通过调用线程的start()方法来实现的。
下面一个例子实践了如何通过上述两种方法创建线程并启动它们:
// 通过Thread类的子类创建的线程;
class thread1 extends Thread
{ file://自定义线程的run()方法;
public void run()
{
System.out.println("Thread1 is running…");
}
}
file://通过Runnable接口创建的另外一个线程;
class thread2 implements Runnable
{ file://自定义线程的run()方法;
public void run()
{
System.out.println("Thread2 is running…");
}
}
file://程序的主类´
class Multi_Thread file://声明主类;
{
plubic static void mail(String args[]) file://声明主方法;
{
thread1 threadone=new thread1(); file://用Thread类的子类创建线程;
Thread threadtwo=new Thread(new thread2()); file://用Runnable接口类的对象创建线程;
threadone.start(); threadtwo.start(); file://strat()方法启动线程;
}
}
责编:豆豆技术应用