java同步锁synchronized的使用
synchronized 同步锁 ,首先需要明白同步和异步的关系,所谓同步,就是事情需要一步一步的做,反之为异步,异步就是在做这件事的时候也可以做其他的事情。
这是上了锁之后的情况
public class Threadddddddddddd implements Runnable{
@Override
public synchronized void run() {
for(int i =0;i<5;i++){
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"------"+i);
}
}
public static void main(String[] args) {
Threadddddddddddd threadddddddddddd = new Threadddddddddddd();
Thread thread = new Thread(threadddddddddddd, "a");
thread.start();
Thread thread1 = new Thread(threadddddddddddd, "b");
thread1.start();
}
}
输出结果
a------0
a------1
a------2
a------3
a------4
b------0
b------1
b------2
b------3
b------4
未上锁
public class Threadddddddddddd implements Runnable{
@Override
public void run() {
for(int i =0;i<5;i++){
try {
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"------"+i);
}
}
public static void main(String[] args) {
Threadddddddddddd threadddddddddddd = new Threadddddddddddd();
Thread thread = new Thread(threadddddddddddd, "a");
thread.start();
Thread thread1 = new Thread(threadddddddddddd, "b");
thread1.start();
}
}
输出结果:
a------0
b------0
a------1
b------1
a------2
b------2
a------3
b------3
a------4
b------4