cari

Rumah  >  Soal Jawab  >  teks badan

java - 控制并发线程数

高洛峰高洛峰2802 hari yang lalu981

membalas semua(2)saya akan balas

  • 怪我咯

    怪我咯2017-04-18 10:48:36

    Jika anda memahami mekanisme pelaksanaan semaphore, maka soalan ini juga mempunyai maksud yang sama.

    public class Test {
    
        private final Integer maxCounter = 3;
        private Integer current = 0;
    
        public void call1() {
            //在这里补充代码
            synchronized (this) {
                try {
                    while (current.equals(maxCounter)) { // 请求 到达上限
                        wait();
                    }
                } catch (InterruptedException ex) {
                }
                current++;
                notifyAll();
            }
    
            call2(current);
    
            synchronized (this) {
                try {
                    while (current == 0) {
                        wait();
                    }
                } catch (InterruptedException ex) {
                }
                current--;
                notifyAll();
            }
        }
    
        private void call2(Integer current) {
    
            System.out.println(Thread.currentThread().getName() + ": I'm called " + current);
    
            // 下面的休眠 2 秒钟用于测试
            try {
                Thread.sleep(2000);
            } catch (InterruptedException ex) {
                ex.printStackTrace(System.err);
            }
        }
    
        static class TestThread implements Runnable {
    
            private Test t;
    
            public TestThread(Test t) {
                this.t = t;
            }
    
            @Override
            public void run() {
                t.call1();
            }
        }
    
        public static void main(String[] args) {
            Test t1 = new Test();
            TestThread tt = new TestThread(t1);
            for (int i = 0; i < 10; i++) {
                Thread t = new Thread(tt, "Thread-" + i);
                t.start();
            }
        }
    }

    Jalankan kod ini, anda boleh mendapati bahawa hanya 3 utas (maxCounter) dijalankan paling banyak setiap 2 saat.

    balas
    0
  • PHPz

    PHPz2017-04-18 10:48:36

    Gunakan CountDownLatch. . .

    balas
    0
  • Batalbalas