2013-11-21 121 views
3

我有一個線程可以從執行開始每秒打印經過時間,另一個線程每15秒打印一條消息。第一個線程應該更新線程之間共享的時間變量,並在每次更新時間變量時通知其他線程讀取時間變量。這是我目前的:Java通知其他線程

public class PingPong implements Runnable 
{ 
    private static final int REPETITIONS = 4; 

String curName = ""; 
int currentTime = 0; 

Thread t1; 
Thread t2; 

PingPong() { 
    t1 = new Thread(this, "Admin"); 
    t1.start(); 

    t2 = new Thread(this, "Admin1"); 
    t2.start(); 

} 

public void run() { 
try { 
curName = Thread.currentThread().getName(); 

if(curName.equals(t1.getName())){ 
    for (int i=1; i<REPETITIONS; i++) { 
     System.out.println(Thread.currentThread().getName() + ": " + i); 
     Thread.sleep(1000); 
     // System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getState()); 
     System.out.println(t1.getName()); 
     currentTime++; 
    } 
} 
/*else if(curName == t2){ 
    System.out.println("Thread 2"); 
}*/ 
System.out.println(currentTime);  


} catch (InterruptedException e) {  
     return; // end this thread 
} 
} 

public static void main(String[] args) { 
    new PingPong(); 
} 
} 

我是非常新的線程,我不知道如果我正在實施我已經正確的。另外,我不知道如何通知另一個線程。我覺得我現在不在正確的道路上。

如果有人有任何幫助,它真的很感激!

+0

我的問題正確地得到你的問題,以及我從你的問題中瞭解到的是你需要'線程來溝通自己'。查看[Java併發](http://www.vogella.com/articles/JavaConcurrency/article.html)和[Java Callable](http://www.journaldev.com/1090/java-callable-future-example ) –

回答

1

嘗試此代碼:

class T1 extends Thread 
{ 
    private SharedClass s; 
    private int t; 
    T1 (SharedClass s) 
    { 
     this.s = s; 
    } 

    public void run() 
    { 
     while(true) { 
     try { 
      Thread.sleep(1000); 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     s.setSharedTime (++t); 
     System.out.println (t + " displayed by T1"); 
     } 
    } 
} 

class T2 extends Thread { 
    private SharedClass s; 

     T2 (SharedClass s) 
     { 
      this.s = s; 
     } 

     public void run() 
     { 
      while(true) { 
      int t; 
      t = s.getSharedTime(); 
      System.out.println (t + " displayed by T2 after 15 seconds."); 
      } 
     } 
} 

public class SharedClass { 
private int time; 
private boolean shareable = true; 

public static void main(String[] args) { 
    SharedClass s = new SharedClass(); 
    new T1 (s).start(); 
    new T2 (s).start(); 
} 
synchronized void setSharedTime (int c) 
{ 
    while (!shareable) 
     try 
     { 
     wait(); 
     } 
     catch (InterruptedException e) {} 

    this.time = c; 
    if(c%15==0) 
    shareable = false; 
    notify(); 
} 

synchronized int getSharedTime() 
{ 
    while (shareable) 
     try 
     { 
     wait(); 
     } 
     catch (InterruptedException e) { } 

    shareable = true; 
    notify(); 

    return time; 
} 
} 

在Java線程是輕量級進程和由單個CPU共享。而且java語句也需要一些時間來執行。該程序不能保證在15秒的時間間隔內運行,但大約需要15秒。