```java
package 自旋锁的实现;
import java.util.ArrayList;
import java.util.List;
public class Echang {
public volatile int l = 0;
public final Integer lock = 0;
public int swap(int s) {
synchronized (lock) {
int temp = l;
l = s;
return temp;
}
}
public void lock(int i) {
while (swap(i) != 0) {
}
}
public void unlock() {
this.l = 0;
}
public static void main(String[] args) {
Echang lock = new Echang();
List threadList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
lock.lock(1);
System.out.println(Thread.currentThread().getName() + "获取到锁");
try {
Thread.sleep(2000);
} catch (Exception e) {
}
lock.unlock();
}
});
t.setName("线程" + i);
threadList.add(t);
}
for (int i = 0; i < 10; i++) {
threadList.get(i).start();
}
}
}