gpt4 book ai didi

java - 线程不同时执行

转载 作者:行者123 更新时间:2023-12-01 12:58:14 26 4
gpt4 key购买 nike

我有三个线程,每个线程必须定期对同一类(Q)的实例(q)进行一些操作(这就是我在方法 somecheck 中使用 Thread.sleep() 的原因)。主要任务是让线程不同时执行,因此同一时间只能执行一个线程。我试图将每个线程的run方法的内容放入synchronized(q){}中,但我不明白在哪里放置notify和wait方法。

class Q {
boolean somecheck(int threadSleepTime){
//somecheck__section, if I want to stop thread - return false;

try{
Thread.sleep(threadSleepTime);
} catch (InterruptedException e) {
}
return true;
}
}



class threadFirst extends Thread {
private Q q;
threadFirst(Q q){this.q=q;}

public void run(){
do{
//Working with object of class Q
}
while(q.somecheck(10));
}
}

class threadSecond extends Thread {
private Q q;
threadSecond(Q q){this.q=q;}

public void run(){
do{
//Working with object of class Q
}
while(q.somecheck(15));
}
}

class threadThird extends Thread {

private Q q;
threadThird(Q q){this.q=q;}

public void run(){
do{
//Working with object of class Q
}
while(q.somecheck(20));
}
}

class run{
public static void main(String[] args) {
Q q = new Q();
threadFirst t1 = new threadFirst(q);
threadSecond t2 = new threadSecond(q);
threadThird t3 = new threadThird(q);
t1.start();
t2.start();
t3.start();
}
}

最佳答案

如果您在所有方法中使用 synchronized block ,则无需放置任何 notify()wait() 方法,例如:

class threadFirst extends Thread {
...
public void run() {
synchronized (q) {
//your loop here
}
}
...
}

关于java - 线程不同时执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23722770/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com