Java 中创建线程,既可通过继承 Thread 类(匿名类/非匿名类)的方式创建,也可通过实现Runnable接口(匿名类/非匿名类)的方式创建,具体案例如下:
ThreadCases.java
/**
* 线程类定义,用于线程创建应用案例演示
*/
class ThreadClass1 extends Thread
{
//计数器,用于记录线程执行情况
private int count = 10;
/**
* 重写Thread.run()方法
*/
public void run()
{
while (true)
{
//打印count变量
System.out.print(“Count=”+count+” “);
//使count变量自减,当自减为0时,退出循环
if (0 == –count)
{
//打印换行
System.out.println();
return;
}
}//while (true)
}//public void run()
}//class ThreadClass1 extends Thread
/**
* 线程运行类定义,用于线程创建应用案例演示
*/
class RunnClass1 implements Runnable
{
//计数器,用于记录线程执行情况
private int count = 10;
/**
* 重写Runnable.run()方法
*/
public void run()
{
while (true)
{
//打印count变量
System.out.print(“Count=”+count+” “);
//使count变量自减,当自减为0时,退出循环
if (0 == –count)
{
//打印换行
System.out.println();
return;
}
}//while (true)
}//public void run()
//..
}//class RunnClass1 implements Runnable
/**
* 线程案例控制类
*/
public class ThreadCases
{
//线程创建,执行控制时间
private static final long CREATE_CTRL_TIME = 20;
/**
* 等待一会时间,用于执行顺序控制
* @param millis :[IN]等待的时间(单位:毫秒)
*/
protected static void waitForMoment(long millis)
{
try
{
Thread.sleep(millis);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}//public void waitMoment(long millis)
public static void main(String[] args)
{
System.out.println(“/////////////////线程创建(方式1:继承Thread类-非匿名类),应用案例演示/////////////////”);
// 实例化 线程对象
ThreadClass1 thread1 = new ThreadClass1();
//线程启动
thread1.start();
//等待一会时间,让线程结束
waitForMoment(CREATE_CTRL_TIME);
System.out.println(“/////////////////线程创建(方式2:继承Thread类-匿名类),应用案例演示/////////////////”);
//实例化线程对象
Thread thread2 = new Thread()
{
//计数器,用于记录线程执行情况
private int count = 10;
/**
* 重写Thread.run()方法
*/
public void run()
{
while (true)
{
//打印count变量
System.out.print(“Count=”+count+” “);
//使count变量自减,当自减为0时,退出循环
if (0 == –count)
{
//打印换行
System.out.println();
return;
}
}//while (true)
}//public void run()
};//Thread thread2 = new Thread()
//线程启动
thread2.start();
//等待一会时间,让线程结束
waitForMoment(CREATE_CTRL_TIME);
System.out.println(“/////////////////线程创建(方式3:实现Runnable接口-非匿名类),应用案例演示/////////////////”);
//实例化线程对象
Thread thread3 = new Thread(new RunnClass1());
//线程启动
thread3.start();
//等待一会时间,让线程结束
waitForMoment(CREATE_CTRL_TIME);
System.out.println(“/////////////////线程创建(方式4:实现Runnable接口-匿名类),应用案例演示/////////////////”);
//实例化线程对象
Thread thread4 = new Thread(new Runnable()
{
//计数器,用于记录线程执行情况
private int count = 10;
/**
* 重写Runnable.run()方法
*/
public void run()
{
while (true)
{
//打印count变量
System.out.print(“Count=”+count+” “);
//使count变量自减,当自减为0时,退出循环
if (0 == –count)
{
//打印换行
System.out.println();
return;
}
}//while (true)
}//public void run()
});//Thread thread4 = new Thread(new Runnable()
//线程启动
thread4.start();
//等待一会时间,让线程结束
waitForMoment(CREATE_CTRL_TIME);
//..
}//public static void main(
}//public class ThreadCases
运行以上代码,可得到如下结果: