我想解决线程问题。我已经链接了类型为myList
的列表,这些列表应该对数字求和,而没有任何线程阻塞它们。但是,当我使用synchronized
关键字时,线程将被阻塞。如何修改我的代码以使用“越过上锁”?
我的列表类别:
public class myList<T> {
private final Object Lock;
private Node<T> first;
private class Node<K> {
private K elem;
private Node<K> prev;
private Node<K> next;
private Node(final K elem, final Node<K> prev, final Node<K> next) {
this.elem = elem;
this.prev = prev;
this.next = next;
}
}
public myList() {
this.Lock = new Object();
this.first = null;
}
public T get(final int i) {
synchronized (this.Lock) {
Node<T> node = this.first;
for (int j = 0; j < i; j++) {
node = node.next;
}
}
public boolean add(final T e) {
synchronized (this.Lock) {
if (this.first != null) {
Node<T> node= this.first;
while (node.next != null) {
node= node.next;
}
node.next = new Node<>(e, ptr, null);
} else {
this.first = new Node<>(e, null, null);
}
return true;
}
}
主要方法:
public class Main {
static myList<Integer> list;
static Runnable sum(final int start, final int end, final int expected) {
return () -> {
int sum = 0;
for (int i = start; i < end; i++) {
sum += list.get(i);
}
if (sum != expected) {
System.out.println("Error in Thread");
}
};
}
public static void main(final String[] args) throws InterruptedException {
Thread thread0, thread1;
list = new ThreadsafeSimplifiedList<>();
for (int i = 0; i < 2500; i++) {
list.add(i);
}
thread0 = new Thread(sliceSum(0, 1250, 780625));
thread1 = new Thread(sliceSum(1250, 2500, 2343125));
thread0.start();
thread1.start();
thread0.join();
thread1.join();
System.out.printf("%s, %d", list.getClass().toString(), System.currentTimeMillis());
}
}
在此示例中,我根本看不到为什么需要同步,因为没有并发添加或并发添加和获取。