[英]Threads execute not at the same time
I have three threads, each thread have to do some manipulation with the instance(q) of same class (Q), periodically (That's why I use Thread.sleep() in the method somecheck). 我有三个线程,每个线程必须定期对同一类(Q)的instance(q)进行一些操作(这就是为什么我在somecheck方法中使用Thread.sleep()的原因)。 Main task is to make thread execute not at the same time, so at one time can execute only one thread.
主要任务是使线程不能同时执行,因此一次只能执行一个线程。 I tried to put content of run method each thread into synchronized (q){}, but I do not understand where to put notify and wait methods.
我试图将每个线程的run方法的内容放入同步的(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();
}
}
You don't need to put any notify()
and wait()
methods if you use synchronized
blocks inside all of the methods, for example: 如果在所有方法中使用
synchronized
块,则无需放置任何notify()
和wait()
方法,例如:
class threadFirst extends Thread {
...
public void run() {
synchronized (q) {
//your loop here
}
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.