【編程練習(xí)】2個(gè)線程A,B(A只能打印奇數(shù),B只能打印偶數(shù))分別按照整體順序打印

package jayxigua.coding.zfb._20180513;

public class MultiThreadPrint {

    public final static Integer MAX = 100;
    public static int global = 0;

    /**
     * 問(wèn)題描述:2個(gè)線程A,B(A只能打印單數(shù),B只能打印雙數(shù))分別按照整體順序打印1,2,3,4...99,100 
     * 技術(shù)點(diǎn):多線程,同步控制,易擴(kuò)展(例如需要支持3,4個(gè)線程時(shí))
     * 難度:★★★☆
     * 
     * @author jayxigua
     *
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

//      new Thread(new MyThread(-2, 3)).start();
//      new Thread(new MyThread(-1, 3)).start();
//      new Thread(new MyThread(0, 3)).start();
        
        new Thread(new MyThread(-1, 2)).start();
        new Thread(new MyThread(0, 2)).start();

    }

}

class MyThread implements Runnable {

    int value;
    int offset;

    public MyThread(int value, int offset) {
        super();
        this.value = value;
        this.offset = offset;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public int getOffset() {
        return offset;
    }

    public void setOffset(int offset) {
        this.offset = offset;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        while (value + offset <= MultiThreadPrint.MAX) {

            // System.out.println("[debug] 線程名 " + Thread.currentThread().getName() + "value
            // =" + value + ", global =" + MultiThreadPrint.global);
            synchronized (MultiThreadPrint.MAX) {
                if (value + offset == MultiThreadPrint.global + 1) {

                    value = value + offset;
                    MultiThreadPrint.global = value;
                    System.out.println("線程名 " + Thread.currentThread().getName() + ",打印值 " + value);
                } else {

                }
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容