標籤:列印 pre out thread 多線程 art closed ack alt
兩個線程,一個列印1-100的奇數,一個列印1-100的偶數;要求:線程1列印5個之後,線程2開始列印,線程2列印5個之後,線程1再開始列印,以此迴圈。
Code:
package com.qhong;public class Main { /* * 兩個線程,一個列印1-100的奇數,一個列印1-100的偶數;要求:線程1列印5個之後,線程2開始列印,線程2列印5個之後,線程1再開始列印,以此迴圈。 */ private static int state = 1; private static int num1 = 1; private static int num2 = 2; public static void main(String[] args) { // TODO Auto-generated method stub final Main t=new Main(); new Thread(new Runnable(){ @Override public void run(){ while(num1<100){ //兩個線程都用t對象作為鎖,保證每個交替期間只有一個線程在列印 synchronized(t){ // 如果state!=1, 說明此時尚未輪到線程1列印, 線程1將調用t的wait()方法, 直到下次被喚醒 if(state!=1){ try{ t.wait(); }catch(InterruptedException e){ e.printStackTrace(); } } // 當state=1時, 輪到線程1列印5次數字 for(int j=0;j<5;j++){ System.out.println(num1); num1 +=2; } // 線程1列印完成後, 將state賦值為2, 表示接下來將輪到線程2列印 state = 2; // notifyAll()方法喚醒在t上wait的線程2, 同時線程1將退出同步代碼塊, 釋放t鎖 t.notifyAll(); } } } }).start(); new Thread(new Runnable(){ @Override public void run(){ while(num2<100){ synchronized(t){ if(state!=2){ try{ t.wait(); }catch(InterruptedException e){ e.printStackTrace(); } } for(int i=0;i<5;i++){ System.out.println(num2); num2 +=2; } state=1; t.notifyAll(); } } } }).start(); }}
Output:
135792468101113151719121416182021232527292224262830313335373932343638404143454749424446485051535557595254565860616365676962646668707173757779727476788081838587898284868890919395979992949698100
View Code
http://blog.csdn.net/junli_chen/article/details/49584187
Java多線程,線程交替執行