代码:
package haxi;
public class dodo
{
// 主程序入口
public static void main(String[] args)
{
// 创建 OddPrinter 和 EvenPrinter 的对象,并将它们传递给 Thread 的构造函数来创建线程对象
//Thread name为线程名字,这里叫1和2
Runnable r1 = new OddPrinter("Thread 1");
Runnable r2 = new EvenPrinter("Thread 2");
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
// 启动线程
t1.start();
t2.start();
}
// 定义 OddPrinter 类,实现 Runnable 接口
public static class OddPrinter implements Runnable
{
private String threadName;
// 构造函数,用于设置线程的名字
public OddPrinter(String threadName)
{
this.threadName = threadName;
}
// 实现 run() 方法,用于打印1~50之间的奇数
public void run()
{
for (int i = 1; i <= 50; i += 2)
{
System.out.println(threadName + ": " + i);
}
}
}
// 定义 EvenPrinter 类,实现 Runnable 接口
public static class EvenPrinter implements Runnable
{
private String threadName;
// 构造函数,用于设置线程的名字
public EvenPrinter(String threadName)
{
this.threadName = threadName;
}
// 实现 run() 方法,用于打印1~50之间的偶数
public void run()
{
for (int i = 2; i <= 50; i += 2)
{
System.out.println(threadName + ": " + i);
}
}
}
}