synchronized代码块可以使一部分代码不能同时运行,最大的提高了线程的运行效率和安全性
package sync;
public class syncDemo {
public static void main(String[] args) {
Shop s = new Shop();
Thread hlw = new Thread(){
public void run(){
s.buy();
}
};
Thread sj = new Thread(){
public void run(){
s.buy();
}
};
hlw.setName("葫芦娃");
sj.setName("爷爷");
hlw.start();
sj.start();
}
}
class Shop{
/**
* 使用同步方法,挑衣服和试衣服不能同时进行
*/
// public synchronized void buy(){
public void buy(){
Thread t = Thread.currentThread();
System.out.println("开始挑衣服");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (this) {
System.out.println(t.getName() + "开始进入试衣间");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(t.getName()+"离开试衣间");
}
}
}
- 也可以修饰类
package sync;
public class SyncDemo3 {
public static void main(String[] args) {
Boo b = new Boo();
Thread t1 = new Thread(){
public void run(){
b.dosome();
}
};
Thread t2 = new Thread(){
public void run(){
b.dosome();
}
};
t1.start();
t2.start();
}
}
class Boo{
public static synchronized void dosome(){
Thread t = Thread.currentThread();
System.out.println(t.getName()+"执行方法");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(t.getName()+"方法执行完毕");
}
}
- 互斥锁
当一个类的两个不同方法不能同时运行,就可以使用synchronized修饰他们,形成互斥锁。即便多个线程调用这两个方法,也不能同时运行了。
package sync;
public class SyncDemo4 {
public static void main(String[] args) {
Foo f = new Foo();
Thread t1 = new Thread(){
public void run(){
f.abc();
}
};
Thread t2 = new Thread(){
public void run(){
f.xyz();
}
};
t1.setName("气管 ");
t2.setName("食管");
t1.start();
t2.start();
}
}
class Foo{
public synchronized void abc(){
Thread t = Thread.currentThread();
System.out.println(t.getName()+"开始吸气...");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(t.getName()+"吸气完毕");
}
public synchronized void xyz(){
Thread t = Thread.currentThread();
System.out.println(t.getName()+"开始吞咽...");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(t.getName()+"吞咽完毕");
}
}