【发布时间】:2014-05-18 14:04:58
【问题描述】:
我有三个线程,每个线程必须定期对同一类 (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();
}
}
【问题讨论】:
-
是的!一切正常,但线程不同步,线程同时执行。
-
你的代码有很多错误,我们很难处理。
-
这段代码甚至无法编译,要么按照已经提出的要求修复它,要么将其删除
-
你是对的!我已经修好了!
标签: java multithreading