溫馨提示×

java多線程如何交替打印

小億
81
2024-09-05 09:40:00
欄目: 編程語言

在Java中,可以使用synchronized關鍵字和wait()notify()方法實現(xiàn)多線程交替打印。下面是一個簡單的示例:

public class AlternatePrinting {
    private static final Object lock = new Object();
    private static int counter = 1;

    public static void main(String[] args) {
        Thread t1 = new Thread(new PrintTask("Thread-1", 2), "Thread-1");
        Thread t2 = new Thread(new PrintTask("Thread-2", 1), "Thread-2");

        t1.start();
        t2.start();
    }

    static class PrintTask implements Runnable {
        private String threadName;
        private int targetNumber;

        public PrintTask(String threadName, int targetNumber) {
            this.threadName = threadName;
            this.targetNumber = targetNumber;
        }

        @Override
        public void run() {
            while (counter <= 10) {
                synchronized (lock) {
                    if (counter % 2 == targetNumber) {
                        System.out.println(threadName + ": " + counter++);
                        lock.notify();
                    } else {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}

在這個示例中,我們創(chuàng)建了兩個線程t1t2,分別打印奇數(shù)和偶數(shù)。我們使用一個全局變量counter來記錄當前需要打印的數(shù)字,并使用一個鎖對象lock來確保線程間的同步。

counter為奇數(shù)時,線程t1獲得鎖并打印數(shù)字,然后調用lock.notify()喚醒等待的線程t2。接著,線程t1調用lock.wait()釋放鎖并進入等待狀態(tài)。當counter為偶數(shù)時,線程t2獲得鎖并打印數(shù)字,然后調用lock.notify()喚醒等待的線程t1。接著,線程t2調用lock.wait()釋放鎖并進入等待狀態(tài)。這樣,兩個線程就可以交替打印數(shù)字。

0