两个线程交替打印 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(); } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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。