3

我有一个线程从执行开始每秒打印经过的时间,另一个线程每十五秒打印一条消息。第一个线程应该更新一个线程间共享的时间变量,并在每次更新时间变量时通知其他线程读取时间变量。这是我目前拥有的:

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();
}
}

我对线程很陌生,我不确定我是否正确地实现了我已经拥有的东西。另外,我不知道如何通知另一个线程。我觉得我目前没有走在正确的道路上。

如果有人有任何帮助,非常感谢!

4

1 回答 1

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 秒。

于 2013-11-21T06:25:04.430 回答