我们可以定义一个类,使其实现Runnable接口,然后将该类的实例作为构建Thread变量构造函数的参数。示例代码如下:
实现Runnable接口以创建线程
class MyRunnable implements Runnable
{
public void run()
{
for (int i =0; i < 5; i++)
{
System.out.println("Thread " + Thread.currentThread().getName() + " is running.");
}
System.out.println("Thread " + Thread.currentThread().getName() + " is finished.");
}
}
public static void createThreadByRunnable()
{
MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
|
|