我的问题编号1:
我有一个类(称为SyncClass
),该类负责在2个实例方法(称为test1()和test2())中创建同步块。 test1()应该将整数增加1,然后将其打印出来,而test2()应该做同样的事情。只要值小于10,这些方法就应该递增整数。因此,基本上,当test1()将值递增1时,应将其交给另一个方法test2() 在满足条件之前应该做同样的事情。 目前这些2
方法具有wait(2000),因为如果我有一个没有限制的简单等待,则该程序将继续执行,只将部分结果打印到屏幕上,然后挂起。 有一定可能是一个更好的等待来解决它,而无需超时,还是?我的问题编号2:
I有一个外部类(称为TheRunner
)与其他部件类(称为InnerRunner),其中都实现,其中外类具有的run()可运行 - 方法来运行TEST1() - 方法和内部类运行TEST2() - 方法。 是否有没有办法,我只能有一个)类实现Runnable运行两个TEST1(和TEST2()内它的方法(即运行()内 - 方法)?SyncClass的代码如下:
package test;
public class SyncClass {
int i = 0;
boolean b = true;
public void test1() {
synchronized (this) {
while((b == true) && (i < 10)) {
i++;
System.out.println("test 1:");
System.out.println(i);
b = false;
try {
wait(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public void test2() {
synchronized (this) {
while((b == false) && (i < 10)) {
i++;
System.out.println("test 2:");
System.out.println(i);
b = true;
try {
wait(2000);
notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
然后我有了另一个实现Runnable的类来运行上述方法:
package test;
public class TheRunner implements Runnable {
SyncClass sync;
public TheRunner(SyncClass sync) {
this.sync = sync;
}
@Override
public void run() {
sync.test1();
}
class InnerRunner implements Runnable{
SyncClass sync;
public InnerRunner(SyncClass sync) {
this.sync = sync;
}
@Override
public void run() {
sync.test2();
}
}
public static void main(String[] args) {
SyncClass sync = new SyncClass();
TheRunner runner = new TheRunner(sync);
TheRunner.InnerRunner innerRunner = runner.new InnerRunner(sync);
Thread t1 = new Thread(runner);
Thread t2 = new Thread(innerRunner);
t1.start();
t2.start();
}
}
如果我删除了wait(2000)并用简单的wait()替换,那么输出将仅为:
test1:1
test2:2
..但它应该持续到10,即下一次迭代应为test1的:3,TEST2:4,等等,当我和等待(2000)改变其它。我真的不明白吗?
我在理解多线程应用程序中发生的一些背景问题时遇到问题。我的问题编号1:我有一个类(称为SyncClass),负责创建...
wait
。你应该在真实的代码中使用,是AtomicInteger
但在这里我用的int[]
所以你可以希望了解正在发生的事情。每当您wait
时,都需要确保调用某种形式的notify
。让我们从single