2012-12-09 88 views
18

我想創建兩個線程,一個線程顯示從0到10的偶數,一個線程顯示從1到11的奇數整數。下面的代碼適合設計這個節目?創建兩個線程,一個顯示奇數和其他偶數

public class Mythread { 

    public static void main(String[] args) { 
     Runnable r = new Runnable1(); 
     Thread t = new Thread(r); 
     t.start(); 
     Runnable r2 = new Runnable2(); 
     Thread t2 = new Thread(r2); 
     t2.start(); 
    } 
} 

class Runnable2 implements Runnable{ 
    public void run(){ 
     for(int i=0;i<11;i++){ 
      if(i%2 == 1) 
       System.out.println(i); 
     } 
    } 
} 

class Runnable1 implements Runnable{ 
    public void run(){ 
     for(int i=0;i<11;i++){ 
      if(i%2 == 0) 
       System.out.println(i); 
     } 
    } 
} 
+0

是否你想要做什麼?如果是這樣,那麼我想它是適合的... – ramsinb

+0

你運行它嗎? – Frank

+0

如果您正在比較線程的運行方式/時間,最好是相互調用Thread.start()方法。將't.start();'向下移動到't2.start();' – mcalex

回答

12

我只想改變幾個細節(沒必要在這裏使用模運算符...):

public class Mythread { 

    public static void main(String[] args) { 
     Runnable r = new Runnable1(); 
     Thread t = new Thread(r); 
     Runnable r2 = new Runnable2(); 
     Thread t2 = new Thread(r2); 
     t.start(); 
     t2.start(); 
    } 
} 

class Runnable2 implements Runnable{ 
    public void run(){ 
     for(int i=0;i<11;i+=2) { 
      System.out.println(i); 
     } 
    } 
} 

class Runnable1 implements Runnable{ 
    public void run(){ 
     for(int i=1;i<=11;i+=2) { 
      System.out.println(i); 
     } 
    } 
} 
+0

如果它的a愚蠢的問題,但在這種情況下是否有上下文切換的機會?即即使線程尚未完成但奇數有機會等等。 –

+0

這是一個非常實用和簡單的例子,很容易理解。我只是試圖遵循這個例子的模式,並能夠將線程應用到我的大項目中。 :)感謝這一點。 – p3ace

1

我也想看看使用Java Concurrency,如果你想選擇。 Java Concurrency包中提供的一些功能提供了更高級別的抽象,然後直接使用Thread類並提供更多功能。

對於您的具體情況,您的操作非常合理,但是這些數字的打印順序很重要?你想在賠率之前吃東西嗎?這些問題可以更好地表明最適合您需求的設計。

+0

感謝您的回覆。如果我想讓每個線程都會一個接一個發生,該怎麼辦?我的意思是一個奇數甚至一個奇數甚至等。 – Bernard

+1

在這種情況下,我不會打擾一個線程。爲什麼你認爲你需要一個線程開始?如果你想並行處理,跨進程分發功能,你通常使用一個線程... – ramsinb

3

是的,它很好。但在這種情況下,我認爲你不需要2個線程,因爲操作很簡單。但是,如果你正在練習線程,那麼OK

+2

老實說這是考試中的一個問題。我希望我的老師也像你一樣思考。 – Bernard

+0

是的,他會這樣想的。如果他沒有,你可以說,你已經以「可調整的方式」開發它:D。這意味着,如果您使用1000萬個數字執行相同的任務,則這是答案:D –

1
package thread; 

import org.hibernate.annotations.Synchronize; 

class PrintOdd implements Runnable { 
    int count = -1; 
    private Object common; 

    PrintOdd(Object common) { 
     this.common = common; 
    } 

    @Override 
    public void run() { 
     synchronized (common) { 
      while (count < 1000) { 
       try { 
        common.notifyAll(); 
        System.out.println(count += 2); 
        common.wait(); 
       } catch (InterruptedException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } 
     } 

    } 

} 

class PrintEven implements Runnable { 

    int count = 0; 
    private Object common; 

    PrintEven(Object common) { 
     this.common = common; 
    } 

    @Override 
    public void run() { 
     synchronized (common) { 
      while (count < 1000) { 
       try { 
        common.notifyAll(); 
        System.out.println(count += 2); 
        common.wait(); 
       } catch (InterruptedException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
       } 
      } 
     } 

    } 

} 

public class PrintNatural { 
    public static void main(String args[]) { 
     Object obj = new Object(); 
     Runnable r = new PrintOdd(obj); 
     Thread printOdd = new Thread(r); 

     Runnable r2 = new PrintEven(obj); 
     Thread printEven = new Thread(r2); 

     printOdd.start(); 
     printEven.start(); 

    } 

} 
34

@aymeric答案不會按照它們的自然順序打印數字,但是此代碼將會。最後解釋。

public class Driver { 
    static Object lock = new Object(); 

    public static void main(String[] args) { 
     Thread t1 = new Thread(new Runnable() { 
      public void run() { 

       for (int itr = 1; itr < 51; itr = itr + 2) { 
        synchronized (lock) { 
         System.out.print(" " + itr); 
         try { 
          lock.notify(); 
          lock.wait(); 
         } catch (InterruptedException e) { 
          e.printStackTrace(); 
         } 
        } 
       } 
      } 
     }); 
     Thread t2 = new Thread(new Runnable() { 
      public void run() { 

       for (int itr = 2; itr < 51; itr = itr + 2) { 
        synchronized (lock) { 
         System.out.print(" " + itr); 
         try { 
          lock.notify(); 
          if(itr==50) 
           break; 
          lock.wait(); 
         } catch (InterruptedException e) { 
          e.printStackTrace(); 
         } 
        } 
       } 
      } 
     }); 
     try { 
      t1.start(); 
      t2.start(); 
      t1.join(); 
      t2.join(); 
      System.out.println("\nPrinting over"); 
     } catch (Exception e) { 

     } 
    } 
} 

爲了實現這樣的兩個線程的run方法上面已經被稱爲一前一後,即需要對它們進行同步,我實現,使用鎖。

代碼的工作原理如下:t1.run輸出奇數並通知任何等待的線程它將釋放鎖,然後進入等待狀態。

此時t2.run被調用,它打印下一個偶數,通知其他線程它將釋放它保存的鎖,然後進入等待狀態。

這一直持續到t2.run()中的itr達到50,此時我們的目標已經實現,我們需要殺死這兩個線程。

通過中斷,我避免了在t2.run中調用lock.wait(),並且t2線程因此被關閉,控件現在會轉到t1.run,因爲它正在等待獲取鎖;但是這裏itr的值將大於51,我們將從它的運行()中退出,從而關閉線程。

如果在t2.run()中沒有使用break,雖然我們會在屏幕上看到數字1到50,但是兩個線程將進入死鎖狀態並繼續處於等待狀態。

+1

您是否可以更詳細地解釋您的代碼。添加評論。 – Whitecat

+1

我的意思是在答案中添加註釋,而不是在底部。這將有助於。 – Whitecat

+1

是否保證t1總是首先啓動? –

2

下面是在具有要打印的號碼的共享對象上使用鎖的代碼。它保證了序列與上述解決方案不同。

public class MultiThreadPrintNumber { 
    int i = 1; 

    public synchronized void printNumber(String threadNm) throws InterruptedException{ 

     if(threadNm.equals("t1")){ 
     if(i%2 == 1){ 
      System.out.println(Thread.currentThread().getName()+"--"+ i++); 
      notify(); 
     } else { 
      wait(); 
     } 
     } else if(threadNm.equals("t2")){ 
     if(i%2 == 0){ 
      System.out.println(Thread.currentThread().getName()+"--"+ i++); 
      notify(); 
     } else { 
      wait(); 
     } 
     } 

    } 

    public static void main(String[] args) { 
    final MultiThreadPrintNumber obj = new MultiThreadPrintNumber(); 
    Thread t1 = new Thread(new Runnable() { 

     @Override 
     public void run() { 
     try { 
      while(obj.i <= 10){ 

      obj.printNumber(Thread.currentThread().getName()); 
      } 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     System.out.println("done t1"); 
     } 
    }); 
    Thread t2 = new Thread(new Runnable() { 

     @Override 
     public void run() { 
     try { 
      while(obj.i <=10){ 
      obj.printNumber(Thread.currentThread().getName()); 
      } 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     System.out.println("done t2"); 
     } 
    }); 

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

的輸出如下: t1--1 t2--2 t1--3 t2--4 t1--5 t2--6 t1--7 T2 --8 t1--9 t2--10 完成T2 完成T1

0
public class ThreadExample { 

Object lock = new Object(); 

class ThreadEven implements Runnable { 

    @Override 
    public void run() { 
     int i = 2; 
     while (i <= 20) { 
      synchronized (lock) { 
       System.out.println(i + " "); 
       i = i + 2; 
       lock.notify(); 
       try { 
        lock.wait(); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 

    } 

} 

class ThreadOdd implements Runnable { 

    @Override 
    public void run() { 
     int i = 1; 
     while (i <= 20) { 
      synchronized (lock) { 
       System.out.println(i + " "); 
       i = i + 2; 
       try { 
        lock.notify(); 
        lock.wait(); 
       } catch (InterruptedException e) { 

        e.printStackTrace(); 
       } 
      } 
     } 

    } 

} 

public static void main(String args[]) { 

    ThreadExample example = new ThreadExample(); 
    ThreadExample.ThreadOdd odd = example.new ThreadOdd(); 
    ThreadExample.ThreadEven even = example.new ThreadEven(); 

    Thread oT = new Thread(odd); 
    Thread eT = new Thread(even); 

    oT.start(); 
    eT.start(); 

} 
0
public class OddEvenPrinetr { 
    private static Object printOdd = new Object(); 

    public static void main(String[] args) { 

     Runnable oddPrinter = new Runnable() { 
      int count = 1; 
      @Override 
      public void run() { 
       while(true){ 
        synchronized (printOdd) { 
         if(count >= 101){ 
          printOdd.notify(); 
          return; 
         } 
         System.out.println(count); 
         count = count + 2;            
         try { 
          printOdd.notify(); 
          printOdd.wait(); 
         } catch (InterruptedException e) { 
          e.printStackTrace(); 
         } 
        } 
       } 
      } 
     }; 


     Runnable evenPrinter = new Runnable() { 
      int count = 0; 
      @Override 
      public void run() { 
       while(true){ 
        synchronized (printOdd) { 
         printOdd.notify(); 
         if(count >= 100){      
          return; 
         }          
         count = count + 2; 
         System.out.println(count); 
         printOdd.notify(); 
         try { 
          printOdd.wait(); 
         } catch (InterruptedException e) { 
          e.printStackTrace(); 
         } 
        } 
       } 
      } 
     }; 

     new Thread(oddPrinter).start(); 
     new Thread(evenPrinter).start(); 
    } 
} 
1

Concurr ent包裝:

import java.util.concurrent.ExecutorService; 

    import java.util.concurrent.Executors; 
    import java.util.concurrent.Future; 
    import java.util.concurrent.locks.Condition; 
    import java.util.concurrent.locks.Lock; 
    import java.util.concurrent.locks.ReentrantLock; 
    //=========== Task1 class prints odd ===== 
    class TaskClass1 implements Runnable 
    { 

    private Condition condition; 
    private Lock lock; 
    boolean exit = false; 
    int i; 
    TaskClass1(Condition condition,Lock lock) 
    { 
     this.condition = condition; 
     this.lock = lock; 
    } 
    @Override 
    public void run() { 
     try 
     { 
      lock.lock(); 
      for(i = 1;i<11;i++) 
      { 
       if(i%2 == 0) 
       { 
        condition.signal(); 
        condition.await(); 

       } 
       if(i%2 != 0) 
       { 
        System.out.println(Thread.currentThread().getName()+" == "+i); 

       } 

      } 

     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     }finally 
     { 
      lock.unlock(); 
     } 

    } 

} 
//==== Task2 : prints even ======= 
class TaskClass2 implements Runnable 
{ 

    private Condition condition; 
    private Lock lock; 
    boolean exit = false; 
    TaskClass2(Condition condition,Lock lock) 
    { 
     this.condition = condition; 
     this.lock = lock; 
    } 
    @Override 
    public void run() { 
     int i; 
     // TODO Auto-generated method stub 
     try 
     { 
      lock.lock(); 
      for(i = 2;i<11;i++) 

      { 

       if(i%2 != 0) 
       { 
        condition.signal(); 
        condition.await(); 
       } 
       if(i%2 == 0) 
       { 
        System.out.println(Thread.currentThread().getName()+" == "+i); 

       } 

      } 

     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     }finally 
     { 
      lock.unlock(); 

     } 

    } 

} 
public class OddEven { 

    public static void main(String[] a) 
    { 
     Lock lock = new ReentrantLock(); 
     Condition condition = lock.newCondition(); 
     Future future1; 
     Future future2; 
     ExecutorService executorService = Executors.newFixedThreadPool(2); 

     future1 = executorService.submit(new TaskClass1(condition,lock)); 
     future2 = executorService.submit(new TaskClass2(condition,lock)); 
     executorService.shutdown(); 


    } 


} 
0

package p.Threads;

public class PrintEvenAndOddNum { 

    private Object obj = new Object(); 

    private static final PrintEvenAndOddNum peon = new PrintEvenAndOddNum(); 

    private PrintEvenAndOddNum(){} 

    public static PrintEvenAndOddNum getInstance(){ 
     return peon; 
    } 

    public void printOddNum() { 
     for(int i=1;i<10;i++){ 
      if(i%2 != 0){ 
       synchronized (obj) { 
        System.out.println(i); 

        try { 
         System.out.println("oddNum going into waiting state ...."); 
         obj.wait(); 

        } catch (InterruptedException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } 
        System.out.println("resume...."); 
        obj.notify(); 
       } 
      } 
     } 
    } 

    public void printEvenNum() { 
     for(int i=1;i<11;i++){ 
      if(i%2 == 0){ 
       synchronized(obj){ 
        System.out.println(i); 
        obj.notify(); 
        try { 
         System.out.println("evenNum going into waiting state ...."); 
         obj.wait(); 
         System.out.println("Notifying waiting thread ...."); 
        } catch (InterruptedException e) { 
         // TODO Auto-generated catch block 
         e.printStackTrace(); 
        } 
       } 
      } 
     } 
    } 
} 
3
package javaapplication45; 

public class JavaApplication45 extends Thread { 

    public static void main(String[] args) { 
     //even numbers 
     Thread t1 = new Thread() { 
      public void run() { 
       for (int i = 1; i <= 20; i++) { 
        if (i % 2 == 0) { 
         System.out.println("even thread " + i); 
        } 
       } 
      } 
     }; 
     t1.start(); 
     //odd numbers 
     Thread t2 = new Thread() { 
      public void run() { 
       for (int i = 1; i <= 20; i++) { 
        if (i % 2 != 0) { 
         System.out.println("odd thread " + i); 
        } 
       } 
      } 
     }; 
     t2.start(); 

    } 

} 
0
package com.example; 

public class MyClass { 
    static int mycount=0; 
    static Thread t; 
    static Thread t2; 
    public static void main(String[] arg) 
    { 
     t2=new Thread(new Runnable() { 
      @Override 
      public void run() { 
       System.out.print(mycount++ + " even \n"); 
       try { 
        Thread.sleep(500); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
       if(mycount>25) 
        System.exit(0); 
       run(); 
      } 
     }); 
     t=new Thread(new Runnable() { 
      @Override 
      public void run() { 
       System.out.print(mycount++ + " odd \n"); 
       try { 
        Thread.sleep(500); 
       } catch (InterruptedException e) { 
        e.printStackTrace(); 
       } 
       if(mycount>26) 
        System.exit(0); 
       run(); 
      } 
     }); 
     t.start(); 
     t2.start(); 
    } 
} 
0
public class ThreadClass { 
    volatile int i = 1; 
    volatile boolean state=true; 

    synchronized public void printOddNumbers(){ 

        try { 
         while (!state) { 

          wait(); 
         } 

        } catch (InterruptedException e) { 
         e.printStackTrace(); 
        } 
       System.out.println(Thread.currentThread().getName()+" "+i); 
         state = false; 
         i++; 
         notifyAll(); 

    } 

    synchronized public void printEvenNumbers(){ 

     try { 
      while (state) { 

       wait(); 
      } 

     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
     System.out.println(Thread.currentThread().getName()+" "+i); 
     state = true; 
     i++; 
     notifyAll(); 

    } 
} 

然後調用上面的類像這樣

// I am ttying to print 10 values. 
    ThreadClass threadClass=new ThreadClass(); 

     Thread t1=new Thread(){ 
      int k=0; 
      @Override 
      public void run() { 
       while (k<5) { 
        threadClass.printOddNumbers(); 
        k++; 
       } 
      } 
     }; 
     t1.setName("Thread1"); 
     Thread t2=new Thread(){ 
      int j=0; 
      @Override 
      public void run() { 
       while (j<5) { 
        threadClass.printEvenNumbers(); 
        j++; 
       } 
      } 
     }; 
     t2.setName("Thread2"); 

     t1.start(); 

     t2.start(); 
  1. 在這裏,我想打印1至10個號碼。
  2. 一個線程試圖打印偶數和另一個線程奇數。
  3. 我的邏輯打印奇數後的偶數。對於這個偶數的線程,應該等到從奇數方法通知。
  4. 每個線程都調用5次特定的方法,因爲我試圖只打印10個值。

出認沽:

System.out: Thread1 1 
System.out: Thread2 2 
System.out: Thread1 3 
System.out: Thread2 4 
System.out: Thread1 5 
System.out: Thread2 6 
System.out: Thread1 7 
System.out: Thread2 8 
System.out: Thread1 9 
System.out: Thread2 10 
1

不是答案的上述問題,但是,類似的路線。

程序打印陣列順序的元素,但使用兩個不同的線程來打印相鄰的元件

import java.util.logging.Level; 
import java.util.logging.Logger; 

/** 
* 
* @author ntv 
*/ 
public class PrintLAternateNumber { 
    public static void main(String[] args) { 
     int [] num = {1,2,3,4,5,6}; 
     Printer p = new Printer(); 
     Thread t1 = new Thread(new Thread1(num, p), "Thread1"); 
     Thread t2 = new Thread(new Thread2(num, p), "Thread2"); 
     t1.start(); 
     t2.start(); 
    } 


} 

class Thread1 implements Runnable { 
    int [] num; 
    Printer p ; 
    public Thread1(int[] num, Printer p) { 
     this.num = num; 
     this.p = p; 
    } 

    public void run() { 
     try { 
      print(); 
     } catch (InterruptedException ex) { 
      Logger.getLogger(Thread1.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 

    public void print() throws InterruptedException { 
     int i = 1; 

      while(i < num.length) { 
       synchronized(num) { 
        while (p.evenPrinted) { 
         num.wait(); 
        } 
       } 

       synchronized(num) { 
        p.printEven(Thread.currentThread().getName(), num[i]); 
        i= i + 2; 
        num.notifyAll(); 

       } 
      } 
    } 
} 


class Thread2 implements Runnable { 
    int [] num; 
    Printer p ; 
    public Thread2(int[] num, Printer p) { 
     this.num = num; 
     this.p = p; 
    } 

    public void run() { 
     try { 
      print(); 
     } catch (InterruptedException ex) { 
      Logger.getLogger(Thread2.class.getName()).log(Level.SEVERE, null, ex); 
     } 
    } 

    public void print() throws InterruptedException { 
     int i = 0; 

      while(i < num.length) { 
       synchronized(num) { 
        while (!p.evenPrinted) { 
         num.wait(); 
        } 
       }  

       synchronized(num) { 
        p.printOdd(Thread.currentThread().getName(), num[i]); 
        i = i + 2; 
        num.notifyAll(); 

       } 
      } 
    } 
} 

class Printer { 
    boolean evenPrinted = true; 
    void printEven(String threadName , int i) { 
     System.out.println(threadName + "," + i); 
     evenPrinted = true; 
    } 


     void printOdd(String threadName , int i) { 
     System.out.println(threadName + "," + i); 
     evenPrinted = false; 
    } 
} 
0
public class MyThread { 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 

     Threado o =new Threado(); 
     o.start(); 

     Threade e=new Threade(); 
     e.start();  
    }  
} 


class Threade extends Thread{ 

    public void run(){ 

     for(int i=2;i<10;i=i+2) 
      System.out.println("evens "+i);   
    }  
} 


class Threado extends Thread{ 

    public void run(){ 

     for(int i=1;i<10;i=i+2) 
      System.out.println("odds "+i);   
    }  
} 

OUTPUT: -

賠率1 賠率3 賠率5 賠率7 賠率9 平均分2 平均分4 平均分6 平均分8

0

公共類ConsecutiveNumberPrint {

private static class NumberGenerator { 

    public int MAX = 100; 

    private volatile boolean evenNumberPrinted = true; 

    public NumberGenerator(int max) { 
     this.MAX = max; 
    } 

    public void printEvenNumber(int i) throws InterruptedException { 
     synchronized (this) { 
      if (evenNumberPrinted) { 
       wait(); 
      } 
      System.out.println("e = \t" + i); 
      evenNumberPrinted = !evenNumberPrinted; 
      notify(); 
     } 
    } 

    public void printOddNumber(int i) throws InterruptedException { 
     synchronized (this) { 
      if (!evenNumberPrinted) { 
       wait(); 
      } 
      System.out.println("o = \t" + i); 
      evenNumberPrinted = !evenNumberPrinted; 
      notify(); 
     } 
    } 

} 

private static class EvenNumberGenerator implements Runnable { 

    private NumberGenerator numberGenerator; 

    public EvenNumberGenerator(NumberGenerator numberGenerator) { 
     this.numberGenerator = numberGenerator; 
    } 

    @Override 
    public void run() { 
     for(int i = 2; i <= numberGenerator.MAX; i+=2) 
      try { 
       numberGenerator.printEvenNumber(i); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
    } 
} 

private static class OddNumberGenerator implements Runnable { 

    private NumberGenerator numberGenerator; 

    public OddNumberGenerator(NumberGenerator numberGenerator) { 
     this.numberGenerator = numberGenerator; 
    } 

    @Override 
    public void run() { 
     for(int i = 1; i <= numberGenerator.MAX; i+=2) { 
      try { 
       numberGenerator.printOddNumber(i); 
      } catch (InterruptedException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 
public static void main(String[] args) { 
    NumberGenerator numberGenerator = new NumberGenerator(100); 
    EvenNumberGenerator evenNumberGenerator = new EvenNumberGenerator(numberGenerator); 
    OddNumberGenerator oddNumberGenerator = new OddNumberGenerator(numberGenerator); 
    new Thread(oddNumberGenerator).start(); 
    new Thread(evenNumberGenerator).start(); 

} 

}

0

幾乎所有的是必要的,如果你被要求打印,即使在同步的方式奇數。

public class ThreadingOddEvenNumbers { 

    void main(String[] args) throws InterruptedException { 
     Printer printer = new Printer(57); 
     Thread t1 = new Thread(new MyRunner(printer, true), "EvenPrinter"); 
     Thread t2 = new Thread(new MyRunner(printer, false), "OddPrinter"); 
     t1.start(); 
     t2.start(); 

     t1.join(); 
     t2.join(); 
    } 

} 

class MyRunner implements Runnable { 
    private Printer p; 
    private boolean evenProperty; 

    public MyRunner(Printer p, boolean evenNess) { 
     this.p = p; 
     evenProperty = evenNess; 
    } 

    public void run() { 
     try { 
      print(); 
     } catch (InterruptedException ex) { 
      System.out.println(this.getClass().getName() + " " 
        + ex.getMessage()); 
     } 
    } 


    public void print() throws InterruptedException { 
     while (!p.isJobComplete()) { 
      synchronized (p) { 
       if (evenProperty) 
        while (p.isEvenPrinted()) { 
         System.out.println("wait by: " 
           + Thread.currentThread().getName()); 
         p.wait(); 
         if (p.isJobComplete()) 
          break; 
        } 
       else 
        while (!p.isEvenPrinted()) { 
         System.out.println("wait by: " 
           + Thread.currentThread().getName()); 
         p.wait(); 
         if (p.isJobComplete()) 
          break; 
        } 
      } 

      synchronized (p) { 
       if (evenProperty) 
        p.printEven(Thread.currentThread().getName()); 
       else 
        p.printOdd(Thread.currentThread().getName()); 
       p.notifyAll(); 
       System.out.println("notify called: by: " 
         + Thread.currentThread().getName()); 
      } 
     } 
    } 
} 

class Printer { 
    private volatile boolean evenPrinted; 
    private volatile boolean jobComplete; 
    private int limit; 
    private int counter; 

    public Printer(int lim) { 
     limit = lim; 
     counter = 1; 
     evenPrinted = true; 
     jobComplete = false; 
    } 

    public void printEven(String threadName) { 
     System.out.println(threadName + "," + counter); 
     incrCounter(); 
     evenPrinted = true; 
    } 

    public void printOdd(String threadName) { 
     System.out.println(threadName + "," + counter); 
     incrCounter(); 
     evenPrinted = false; 
    } 

    private void incrCounter() { 
     counter++; 
     if (counter >= limit) 
      jobComplete = true; 
    } 

    public int getLimit() { 
     return limit; 
    } 

    public boolean isEvenPrinted() { 
     return evenPrinted; 
    } 

    public boolean isJobComplete() { 
     return jobComplete; 
    } 
} 
0
public class EvenOddNumberPrintUsingTwoThreads { 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 

     Thread t1 = new Thread() {   
      public void run() { 

       for (int i = 0; i <= 10; i++) { 
        if (i % 2 == 0) { 
         System.out.println("Even : " + i); 
        } 
       } 

      } 
     }; 

     Thread t2 = new Thread() { 
      // int i=0; 
      public void run() { 

       for (int i = 0; i <= 10; i++) { 
        if (i % 2 == 1) { 
         System.out.println("Odd : " + i); 
        } 
       } 

      } 
     }; 
     t1.start(); 
     t2.start(); 
    } 
} 
相關問題