[英]Running two threads in same time ( multithreading?)
我正在嘗試使兩個線程同時工作。 讓我用代碼解釋一下:
運行兩個線程的主類
public static void main(String[] args) {
abThread.move(5);
cdThread.move(5);
}
線程1:
static void move(int i) {
int min = 0;
int max = 100;
while (i > 0) {
int a = ThreadLocalRandom.current().nextInt(min, max + 1);
// try {
// Thread.sleep(100);
// } catch (Exception e) {
// }
if ((a % 2) == 1) {
System.out.println("a");
i -= 1;
continue;
} else {
System.out.println("b");
i -= 1;
continue;
}
}
}
線程2:
static void move(int i) {
int min = 0;
int max = 100;
while (i > 0) {
int a = ThreadLocalRandom.current().nextInt(min, max + 1);
// try {
// Thread.sleep(100);
// } catch (Exception e) {
// }
if ((a % 2) == 1) {
System.out.println("c");
i -= 1;
continue;
} else {
System.out.println("d");
i -= 1;
continue;
}
}
}
即時通訊獲得隨機a / bx 5,其中5個之后即時通訊(c / d)x5
我的目標是獲取a / b,c / d,a / b,c / d ...等等
任何幫助或重定向到某種方式將不勝感激!
編輯:注意,我嘗試了嘗試睡眠,但是它只是將a / b之后的下一個a / b推遲了多長時間。 只有我可以做到的a / b,c / b是
abThread.move(1);
cdThread.move(1);
abThread.move(1);
......
謝謝
由線程而不是主線程執行的工作由初始化該線程的Runnable
決定,或者由其run()
方法的實現決定run()
如果已重寫)。 這些地方之一是您應該放置各種move()
方法的調用的地方。 然后,您的主線程應同時在兩個線程實例上start()
。
這(可能)實現了並行運行的線程,這取決於線程調度和執行資源的可用性。 但是,正如@Alexander所描述的那樣,它不一定在兩個線程的輸出之間產生完美的交替,也不保證一個線程產生的任何輸出將在另一個線程產生的任何輸出之前出現。
如果需要完美的交替,則兩個線程需要彼此同步以輪流使用。 有很多方法可以實現,但如果需要,則需要將其內置到move()
方法中。 低級的老式方法圍繞使用共享對象的wait()
和notify()
/ notifyAll()
方法。 您還可能只將SynchronousQueue
用於兩個輪換的線程,還有許多其他可能性。
如果您真的想嘗試線程,不僅要交替打印字符,還可以嘗試如下操作:
首先,實現Runnable
來保存要由線程運行的代碼:
class Task implements Runnable {
//c1 and c2 are characters to print (a,b and c,d for example)
private final String c1, c2;
//semaphore guarantees the order of threads execution
private final Semaphore sync;
private int i;
Task(int i, String c1, String c2, Semaphore sync) {
this.i = i;
this.c1 = c1;
this.c2 = c2;
this.sync = sync;
}
@Override
public void run() {
try {
int min = 0;
int max = 100;
while (i > 0) {
sync.acquire();
int a = ThreadLocalRandom.current().nextInt(min, max + 1);
if ((a % 2) == 1) {
System.out.println(c1);
i -= 1;
} else {
System.out.println(c2);
i -= 1;
}
sync.release();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
然后創建Semaphore
:
Semaphore sync = new Semaphore(0, true);
創建兩個線程並運行它們:
Thread t1 = new Thread(new Task(10, "a", "b", sync));
Thread t2 = new Thread(new Task(10, "c", "d", sync));
t1.start();
t2.start();
最后釋放信號量,以便等待它的線程之一可以繼續:
sync.release();
線程按照自己的步調運行,並根據操作系統的需要在CPU上進行調度。 如果操作系統使用循環調度(即每個線程轉一圈),則只能期望得到a/b, c/d, a/b, c/d, ...
執行,幾乎可以肯定沒有。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.