我在我的代码中有一个线程问题,应该不会发生 - 但是。所以我正在尝试做一些工作。我会尽量解释我的问题,简单的代码,我可以 - 因为我遇到问题的代码是大,所以在短的代码复杂 :java并发 - 同步块
...................
..................
void createAndRunThreads(){
List<Path> pathList = //read path from DB readPath();
for(Path p : pathList){
RunJob rj = new RunJob(p);
Thred t = new Thread(rj);
t.start();
}
}
class RunJob implements Runnable {
private Path path;
private ExecuteJob execJob;
public RunJob(Path path){
this.path = path;
this.execJob = new ExecuteJob();
}
public void run() {
execJob.execute(path);
}
}
class ExecuteJob {
private static Job curentExecutingJob;
public void execute(Path path){
//here every thread should get different job list from others but this is not happening
//so what happens eventually two threads are executing the same Job at once and it gets messy
List<Job> jobList = getJobsFromPath(path);
for(Job job : jobList) {
curentExecutingJob=job;
//work around that I'm trying to do. So if other thread tries to run the same job has to wait on lock(I dont know if this is posible do)
synchronized(curentExecutingJob){
if(job.getStatus.equals("redy")){
//do sum initialization
//and databese changes
job.run();
}
}
}
}
}
所以我担心的是,如果这会工作 - 我不知道是否锁内的对象是通过内存(需要是确切的对象)或等于(实现相等)
当静态的curentExecutingJob成员有一个值对象在第一个线程和创建的锁(在同步块)和第二个线程的变化值和尝试进入同步块(我期望,我希望是线程2将继续执行和onl Ÿ时间,这将是块时,他会得到DB以前第一个线程得到它)
相同的工作,我不知道这种方法可以做到的,有意识
两个线程都运行下面的代码即内部方法
1 Job j = getJobByIdFromDB(1111);
2 if(j.status.equals("redye")){
3 do staff
4 make database changes
5 j.run();
6 j.state="running";
7 }
的的ThreadA是从JVM在3行执行停止和他的状态从运行到可运行改变,并且被设置在所述轮询等待。
ThreadB由JVM给出机会,ThreadB执行我不想发生的行1,2,3,4,5,6。我想第2,3行输入代码的第一个线程在其他线程的某个人有机会输入相同的代码之前完成
问题完成这个问题是两个线程正在执行不同实例的示例方法同步整个方法不会工作 - 也有其他代码已执行此方法,我不希望这是同步到
所以有解决我的问题 此外,如果我让同步(this.class) {}它将失去多线程的好处和意义
那么,首先,你的变量curentExecutingJob被声明为静态的,并且会被同时覆盖和访问。这种方法并不是很好。你期望用这个方案完成什么? – Martin
你考虑过一个ExecutorService吗?它是一个带有队列的线程池,它确保每个任务仅由一个线程运行。 –