【JAVA】输出1-1000内的奇数

public class test2 {
	public static void main(String[] args) {
		int i;
		for(i=1;i<=1000;i++)
		{
		 if(!(i%2==0)){
			  System.out.println(i);
			  }
		}
}
	}

  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,我们可以使用 `synchronized` 关键字和 `wait()`、`notify()` 方法来实现线程的交替输出。下面是一个示例代码: ```java class OddEvenPrinter { private int count; private int maxCount; public OddEvenPrinter(int maxCount) { this.maxCount = maxCount; this.count = 1; } public synchronized void printOdd() throws InterruptedException { while (count <= maxCount) { if (count % 2 != 0) { System.out.println(count); count++; notify(); } else { wait(); } } } public synchronized void printEven() throws InterruptedException { while (count <= maxCount) { if (count % 2 == 0) { System.out.println(count); count++; notify(); } else { wait(); } } } } public class Main { public static void main(String[] args) { OddEvenPrinter printer = new OddEvenPrinter(100); Thread oddThread = new Thread(() -> { try { printer.printOdd(); } catch (InterruptedException e) { e.printStackTrace(); } }); Thread evenThread = new Thread(() -> { try { printer.printEven(); } catch (InterruptedException e) { e.printStackTrace(); } }); oddThread.start(); evenThread.start(); } } ``` 在这个代码中,我们创建了一个名为 `OddEvenPrinter` 的类,它有一个 `count` 变量来表示当前要输出的数字,和一个 `maxCount` 变量来表示最大的数字。`printOdd()` 方法用于输出奇数,`printEven()` 方法用于输出偶数。 在每个方法中,我们使用 `synchronized` 关键字来确保线程的同步。在 `printOdd()` 方法中,当 `count` 为奇数输出数字并递增,然后调用 `notify()` 方法唤醒等待的线程;如果 `count` 为偶数,则调用 `wait()` 方法使线程等待。在 `printEven()` 方法中同理。 在 `main()` 方法中,我们创建了两个线程 `oddThread` 和 `evenThread`,分别执行 `printOdd()` 和 `printEven()` 方法。然后启动这两个线程,它们将交替输出奇偶数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值