Java.编写一个程序,创建两个线程对象,分别在屏幕上显示1~50之间的奇数和偶数,观察一共有几个线程在运行,各个线程是怎样被处理器执行到的

代码:


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);
            }
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值