synchronized
synchronized 关键字,代表这个方法加锁,相当于不管哪一个线程(例如线程A),运行到这个方法时,都要检查有没有其它线程B(或者C、 D等)正在用这个方法,有的话要等正在使用synchronized方法的线程B(或者C 、D)运行完这个方法后再运行此线程A;没有的话,直接运行。
下面是一个例子
方法1
public class RunThreads implements Runnable{
public static void main(String[] args) {
RunThreads runThreads=new RunThreads();
new Thread(runThreads,"1-->").start();
new Thread(runThreads,"2-->").start();
new Thread(runThreads,"3-->").start();
}
public int tickets =5;
public void run(){
for (int i = 0; i < 50; i++) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (this) {
if (tickets>0) {
System.out.println("线程"+this.tickets--);
}
}
}
}
}
方法2
public class RunThreads1 implements Runnable{
public static void main(String[] args) {
RunThreads runThreads=new RunThreads();
new Thread(runThreads,"1-->").start();
new Thread(runThreads,"2-->").start();
new Thread(runThreads,"3-->").start();
}
public int tickets =5;
public synchronized void sall(){
if (tickets>0) {
System.out.println("线程"+this.tickets--);
}
}
public void run(){
for (int i = 0; i < 50; i++) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.sall();
}
}
}
synchronized 方法用的多的话 会形成死锁
下面是一个例子
public class Zhangsan {
public synchronized void say(Lisi ls){
System.out.println(" 先--> 给钱");
ls.give();
}
public synchronized void give(){
System.out.println(" 给了钱 --> 放人 ");
}
}
public class Lisi {
public synchronized void say(Zhangsan zs){
System.out.println("先。。。。。。。。。。。。放人");
zs.give();
}
public synchronized void give(){
System.out.println("再。。。。。。。。给钱");
}
}
public class DeadThreadss implements Runnable{
private Zhangsan zhangsan=new Zhangsan();
private Lisi lisi =new Lisi();
public DeadThreadss(){
new Thread(this).start();
lisi.say(zhangsan);
}
public void run() {
zhangsan.say(lisi);
}
public static void main(String[] args) {
new DeadThreadss();
}
}
运行上面的三个类 可实现死锁的 小例子