gpt4 book ai didi

java - 1 类中的同步线程

转载 作者:行者123 更新时间:2023-12-01 23:57:51 24 4
gpt4 key购买 nike

我一直在寻找一种成功使用多线程和同步的方法。我尝试过使用 wait() 和 notification(),但我的线程仍然不同步。我有一个更大的项目,但简而言之,我需要它以预定的次数运行带有 setter 方法的线程(在本例中为 thread1),并且在每次“设置”之后,我需要带有 getter 方法的线程(thread2)运行并获取对象。我已经看过许多其他示例,但我似乎无法解决它,因此任何帮助或解释为什么这不起作用将不胜感激。

有时,当线程 1 首先运行时,这会起作用,但有时线程 2 首先运行,因此同步不起作用。

谢谢。

import java.util.ArrayList;

public class ThreadTest{

private ArrayList<Object> myList;

public ThreadTest(){

myList = new ArrayList<Object>();

Thread thread1 = new Thread(){
public void run(){
for(int i = 0; i < 10; i++){
addToList("" + i);
}
}
};

Thread thread2 = new Thread(){
public void run(){
for(int i = 0; i < 10; i++){
System.out.print(myList.get(i) + " ");
}
}
};

thread1.start();
thread2.start();
}

public synchronized void addToList(String a){
myList.add(a);
notify();
}

public synchronized ArrayList<Object> getList(){
try{
wait();
}
catch (InterruptedException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
return myList;
}

public static void main(String[] args){
new ThreadTest();
}
}

最佳答案

使用BlockingQueue自动进行同步,使用ExecutorService来处理所有Thread

public void doStuff() {
final Object finishSupplying = new Object();
final BlockingQueue<Object> myList = new LinkedBlockingQueue<Object>();
final Runnable supplier = new Runnable() {
public void run() {
for (int i = 0; i < 10; i++) {
myList.add(i);
}
}
};

final Runnable consumer = new Runnable() {
public void run() {
while (true) {
try {
final Object thing = myList.take();
if(thing == finishSupplying) break;
System.out.print(thing + " ");
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
};

final ExecutorService exectutorService = Executors.newFixedThreadPool(2);
final Future<?> supplierHandle = exectutorService.submit(supplier);
final Future<?> consumerHandle = exectutorService.submit(consumer);
try {
supplierHandle.get();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
} catch (ExecutionException ex) {
//PROBLEMS, handle
}
myList.add(finishSupplying);
try {
consumerHandle.get();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
} catch (ExecutionException ex) {
//PROBLEMS, handle
}
}

完成后请确保shutdown() ExecutorService,否则程序将不会退出。

关于java - 1 类中的同步线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15315414/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com