簡體   English   中英

等待一個線程在Java中完成

[英]Wait for one thread to finish in java

我是java中較新的Threading,我試圖做以下工作。 兩個線程將運行。 線程1從1-10開始打印,然后等待線程2完成11-20打印,然后完成其任務並通知線程1打印21-30,然后線程1也將終止。 這是我使用的代碼:

private Thread thread = null;
private String name = null;
private static Object obj = new Object();
private static int index = 1;

public childThread(Thread t, String name)
{
  this.name = name;
  this.thread = t;
}
public void run()
{      
try
{
  while (true) {
    Thread.sleep(500);
    if (index % 10 == 0 && index == 10) {
      System.out.println("Waiting for Thread2");
      synchronized (obj) {
        obj.notify();
        obj.wait();
      }
    }
    else if (index % 10 == 0 && index == 20) {
      System.out.println("Waiting for Thread1");
      synchronized (obj) {
        obj.notify();
        obj.wait();
      }
    }
    else if(index == 30)
    {
      obj.wait();
    }


    synchronized (obj) {
      System.out.println(name + " ><>< " + index);
      index++;
    }
  }
}
catch(Exception e)
{
}

我得到以下輸出:

Thread2 ><>< 1
Thread1 ><>< 2
Thread2 ><>< 3
Thread1 ><>< 4
Thread2 ><>< 5
Thread1 ><>< 6
Thread1 ><>< 7
Thread2 ><>< 8
Thread2 ><>< 9
Thread1 ><>< 10
Thread2 ><>< 11
Thread1 ><>< 12
Thread2 ><>< 13
Thread1 ><>< 14
Thread2 ><>< 15
Thread1 ><>< 16
Thread2 ><>< 17
Thread1 ><>< 18
Thread2 ><>< 19
Waiting for Thread1
Waiting for Thread1
Thread1 ><>< 20
Thread1 ><>< 21
Thread1 ><>< 22
Thread1 ><>< 23
Thread1 ><>< 24
Thread1 ><>< 25
Thread1 ><>< 26
Thread1 ><>< 27
Thread1 ><>< 28
Thread1 ><>< 29

基於我目前對Java線程的理解。

if(index%10 == 0 && index == 10)塊將通知另一個線程運行並等待另一個線程完成,第二個線程則繼續執行。 現在,它第一次不起作用。 但是,當索引== 20時,線程2停止工作,線程1繼續打印30。

謝謝你的幫助。 :)

這里的根本問題是,您處於競爭狀態,兩個線程同時進入循環。

您需要進行安排,以便僅允許其中一個進入,另一個必須立即等待。

您可以改為嘗試如下所示的循環,這是互斥的。 一個線程將被允許進入並開始遞增,而另一個線程必須停止,直到第一個線程調用obj.wait()為止。

synchronized(obj) {
    while (index < 30) {
       Thread.sleep(500);
       if (index > 0 && index % 10 == 0) {
           obj.notify();
           obj.wait();
       }
       index++;
   }
}

我使用名為Counter的共享對象類編寫了一個簡單的代碼,它將跟蹤計數器的詳細信息,並編寫了兩個線程ThreadOne和ThreadTwo和Main應用程序類,如下所示。

正如其他人所建議的那樣,您可以使用高級鎖定對象,例如信號量或Lock類。

package thread.communication.demo;

public class Counter {

private int count = 1;

private boolean lockTrue = false;

public synchronized void incrFirstThread() {

    while (lockTrue) {

        try {
            wait();

        } catch (InterruptedException ex) {
            Logger.getLogger(Counter.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    lockTrue = true;

    for (int i = count; i < count + 10; i++) {
        System.out.println(i + Thread.currentThread().getName());
    }

    count += 10;

    notifyAll();

}

public synchronized void incrSecondThread() {

    while (!lockTrue) {

        try {
            wait();

        } catch (InterruptedException ex) {
            Logger.getLogger(Counter.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    lockTrue = false;

    for (int i = count; i < count + 10; i++) {
        System.out.println(i + Thread.currentThread().getName());
    }

    count += 10;

    notifyAll();
}
}



package thread.communication.demo;

public class ThreadOne extends Thread{

Counter counter;

ThreadOne(Counter counter)
{
    this.counter=counter;
}

@Override
public void run() {

    while (true) {

        counter.incrFirstThread();
    }
}
}

package thread.communication.demo;

public class ThreadTwo extends Thread {

Counter counter;

ThreadTwo(Counter counter)
{
    this.counter=counter;
}

@Override
public void run() {

    while (true) {

        counter.incrSecondThread();
    }
}
}

package thread.communication.demo;

public class ThreadMain {

public static void main(String[] args) {

    Counter counter=new Counter();

    ThreadOne one = new ThreadOne(counter);

    ThreadTwo two = new ThreadTwo(counter);

    one.start();

    two.start();
}
}

輸出如下。

[INFO] [INFO] --- exec-maven-plugin:1.2.1:exec(default-cli)@ MultiThreading ---

1線程-0 2線程-0 3線程-0 4線程-0 5線程-0 6線程-0 7線程-0 8線程-0 9線程-0 10線程-0 11線程-1 12線程-1 13線程-1 14線程-1 15線程-1 16線程-1 17線程- 1 18Thread-1 19Thread-1 20Thread-1 21Thread-0 22Thread-0 23Thread-0 24Thread-0 25Thread-0 26Thread-0 27Thread-0 28Thread-0 29Thread-0 30Thread-0 31Thread-1 32Thread-1 33Thread-1 34線程-1 35Thread-1 36Thread-1 37Thread-1 38Thread-1 39Thread-1 40Thread-1 41Thread-0 42Thread-0 43Thread-0 44Thread-0 45Thread-0 46Thread-0 47Thread-0 48Thread-0 49Thread-0 50Thread-0 51Thread-1 52Thread-1 53Thread-1 54Thread-1 55Thread-1 56Thread-1 57Thread-1 58Thread-1 59Thread-1 60Thread-1

這是一個有效的代碼,希望對您有所幫助

public static void main(String[] args) {
    final Object lock = new Object();
    final Thread t2 = new Thread() {
        public void run() {
            synchronized (lock) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            for(int i = 11; i < 21; i++) System.out.println(i);
        }
    };
    Thread t1 = new Thread() {
        public void run() {
            for(int i = 1; i < 11; i++) System.out.println(i);
            synchronized (lock) {
                lock.notifyAll();
            }
            try {
                t2.join();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            for(int i = 21; i < 31; i++) System.out.println(i);
        }
    };
    t1.start();
    t2.start();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM