了解Java中的多线程

Vivek Vardhan

我正在multithreading用Java学习问题陈述是:假设有一个数据结构可以包含数百万个Integer,现在我要在其中搜索一个键。我想使用2个线程,以便如果其中一个线程找到了密钥,则应将共享的布尔变量设置为false,并且两个线程都应停止进一步处理。

这是我正在尝试的:

public class Test  implements Runnable{
    private List<Integer> list;
    private Boolean value;
    private int key = 27;

    public Test(List<Integer> list,boolean value) {
        this.list=list;
        this.value=value;
    }

    @Override
    public void run() {
        synchronized (value) {
            if(value){
                Thread.currentThread().interrupt();
            }
            for(int i=0;i<list.size();i++){
                if(list.get(i)==key){
                    System.out.println("Found by: "+Thread.currentThread().getName());
                    value = true;
                    Thread.currentThread().interrupt(); 
                }
                System.out.println(Thread.currentThread().getName() +": "+ list.get(i));
            }
        }

    }
}

主要类别是:

public class MainClass {


    public static void main(String[] args) {
        List<Integer> list = new ArrayList<Integer>(101);
        for(int i=0;i<=100;i++){
            list.add(i);
        }

        Boolean value=false;

        Thread t1 = new Thread(new Test(list.subList(0, 49),value));
        t1.setName("Thread 1");

        Thread t2 = new Thread(new Test(list.subList(50, 99),value));
        t2.setName("Thread 2");

        t1.start();
        t2.start();
    }
}

我期望的是:

两个线程将随机运行,并且当任何一个线程遇到27时,两个线程都将被中断。因此,线程1应该不能处理所有输入,类似于线程2。

但是,发生了什么:

两个线程都已完成循环,线程2始终在线程1完成后开始。

Please highlight the mistakes,我仍在学习线程。

我的下一个练习问题将是:任意访问任何共享资源

老弯棍

您不应该在该found标志上获得锁-这只会确保仅一个线程可以运行。而是使该标志static共享,volatile这样就不能被缓存。

另外,您应该更频繁地检查标志。

private List<Integer> list;
private int key = 27;
private static volatile boolean found;

public Test(List<Integer> list, boolean value) {
    this.list = list;
    this.found = value;
}

@Override
public void run() {
    for (int i = 0; i < list.size(); i++) {
        // Has the other thread found it?
        if (found) {
            Thread.currentThread().interrupt();
        }
        if (list.get(i) == key) {
            System.out.println("Found by: " + Thread.currentThread().getName());
            // I found it!
            found = true;
            Thread.currentThread().interrupt();
        }
        System.out.println(Thread.currentThread().getName() + ": " + list.get(i));
    }
}

顺便说一句:您的两个线程均始于0阵列并在阵列上移动-我假设您在此代码中以此为例进行演示,您可以让它们在相反的一端工作,或者它们随机地行走。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章