下面的代码用于同步 myIntArray 是否合法?
它会阻止三个底部方法无序更改 myIntArray 吗?
我希望事情按延迟方法 1、延迟方法 2、方法 3 的顺序发生,而不是在前一个完成对 myIntArray 的更改之前运行而搞砸其中一个。
底部的 3 个方法声明是否需要同步关键字?
底部的 3 个方法是否需要包含 synchronized(myIntArray) 块?
我的同步块应该在 Runnable 周围而不是在它里面吗?
我是否需要通知、等待或加入命令?
public class HelpPlease {
public int myIntArray[] = new int[100];
public void chooseSquare() {
...
Handler handler=new Handler();
final Runnable r = new Runnable()
{
public void run()
{
synchronized(myIntArray) {
delayedMethod1();
}
}
};
handler.postDelayed(r, 1000);
...
Handler handler2=new Handler();
final Runnable r2 = new Runnable()
{
public void run()
{
synchronized(myIntArray) {
delayedMethod2();
}
}
};
handler2.postDelayed(r2, 1000);
...
synchronized(myIntArray) {
method3();
}
}
public void delayedMethod1() {
...
change myIntArray;
otherMethodsABC();
{
public void delayedMethod2() {
...
change myIntArray;
otherMethodsDEF();
}
public void method3() {
...
change myIntArray;
otherMethodsGHI();
}
}
更多细节:处理程序/Runnable 延迟产生有时不同步的事件
编辑:
这有意义吗?运行一个线程等待它完成?不知道如何添加延迟,这就是重点。
//Handler handler=new Handler();
final Runnable r = new Runnable()
{
public void run()
{
delayedMethod();
}
};
//handler.postDelayed(r, COMPUTER_MOVE_DELAY);
ExecutorService es = Executors.newFixedThreadPool(1);
final Future f1 = es.submit(r);
try
{
f1.get();
}
catch (InterruptedException e)
{
throw new RuntimeException(e);
}
catch (ExecutionException e)
{
throw new RuntimeException(e);
}