两个线程交替打印 0~100 的奇偶数
import threading class PrintThread(threading.Thread): def __init__(self, start_num, step, max_num): super(PrintThread, self).__init__() self.start_num = start_num self.step = step self.max_num = max_num def run(self): i = self.start_num while i <= self.max_num: print(i) i += self.step # 创建两个线程,分别打印奇数和偶数 t1 = PrintThread(1, 2, 100) t2 = PrintThread(0, 2, 100) # 启动线程 t1.start() t2.start() # 等待两个线程执行完毕 t1.join() t2.join()
using System; using System.Threading; class PrintThread { private int startNum; private int step; private int maxNum; public PrintThread(int startNum, int step, int maxNum) { this.startNum = startNum; this.step = step; this.maxNum = maxNum; } public void Run() { for (int i = startNum; i <= maxNum; i += step) { Console.WriteLine(i); } } } class Program { static void Main(string[] args) { // 创建两个线程,分别打印奇数和偶数 PrintThread oddThread = new PrintThread(1, 2, 100); PrintThread evenThread = new PrintThread(0, 2, 100); // 启动两个线程 Thread t1 = new Thread(oddThread.Run); Thread t2 = new Thread(evenThread.Run); t1.Start(); t2.Start(); // 等待两个线程执行完毕 t1.Join(); t2.Join(); } }

public class PrintOddEven { private static final Object lock = new Object(); private static volatile int count = 0; public static void main(String[] args) { Thread oddThread = new Thread(new OddPrinter(), "Odd"); Thread evenThread = new Thread(new EvenPrinter(), "Even"); oddThread.start(); evenThread.start(); } static class OddPrinter implements Runnable { public void run() { while (count <= 100) { synchronized (lock) { if (count % 2 == 1) { System.out.println(Thread.currentThread().getName() + ": " + count); count++; lock.notify(); } else { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } static class EvenPrinter implements Runnable { public void run() { while (count <= 100) { synchronized (lock) { if (count % 2 == 0) { System.out.println(Thread.currentThread().getName() + ": " + count); count++; lock.notify(); } else { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } }
在这个实现中,我们使用一个共享对象lock
作为同步锁,并使用volatile
修饰count
变量,以确保不同线程之间的可见性。我们创建两个线程,一个打印奇数,一个打印偶数。每个线程在打印数字之前都会获取锁,如果当前count
变量为奇数或偶数,则打印相应的数字并将count
变量递增。递增后,线程调用lock.notify()
方法通知另一个线程继续执行。如果count
变量不是奇数或偶数,则线程调用lock.wait()
方法释放锁并等待通知。在main()
方法中,我们启动两个线程,使它们交替打印数字,直到count
变量达到 100。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)