1. 程式人生 > >線程練習--主線程執行10次,非主線程執行5次

線程練習--主線程執行10次,非主線程執行5次

ring 練習 run read 存在 -- boolean tac start

public class Test {

    public static void main(String[] args){
        
        MeThread me = new MeThread();
        Thread t = new Thread(me);
        t.start();

        boolean flag = true;
        int i = 1;
        synchronized (me) {
            
            while (flag) {
                System.out.println(Thread.currentThread().getName()
+i); i++; if (i % 10 == 0) { try { me.notify();//Thread.currentThread().notifyAll(); i = 0; me.wait();//wait()必須放在notify()後邊,先喚醒再自己暫停,不存在先暫停,再喚醒 } catch (InterruptedException e) { e.printStackTrace(); }
finally { System.out.println("==========="); } } } } } } class MeThread implements Runnable { @Override public synchronized void run() { int i = 0; boolean flag = true;
while (flag) { System.out.println(Thread.currentThread().getName() + i); i++; if (i % 5 == 0) { try { this.notify();//Thread.currentThread().notifyAll(); i = 0; this.wait(); } catch (InterruptedException e) { e.printStackTrace(); }finally { System.out.println("==========="); } } } } }

執行結果

main0
main1
main2
main3
main4
main5
main6
main7
main8
main9
===========
Thread-00
Thread-01
Thread-02
Thread-03
Thread-04
===========
main0
main1
main2
main3
main4
main5
main6
main7
main8
main9
===========
Thread-00
Thread-01
Thread-02
Thread-03
Thread-04
===========

線程練習--主線程執行10次,非主線程執行5次