同步与死锁的问题
比如一个卖票程序,如果多线程同时操作时,就有可能出现卖出票为负数的问题。
例子:用Runnable接口实现多线程,并产生3个线程对象。同时卖五张票
package test2; class MyThread11 implements Runnable { private int ticket = 5; public void run() { for (int i = 0; i < 100; i++) { if (ticket > 0) { try { Thread.sleep(300); } catch (InterruptedException e) { // TODO: handle exception e.printStackTrace(); } System.out.println("卖票:ticket=" + ticket--); } } } } public class SyncDemo01 { public static void main(String[] args) { MyThread11 mt = new MyThread11(); Thread t1 = new Thread(mt); Thread t2 = new Thread(mt); Thread t3 = new Thread(mt); t1.start(); t2.start(); t3.start(); } }
结果:
卖票:ticket=5
卖票:ticket=4
卖票:ticket=3
卖票:ticket=2
卖票:ticket=1
卖票:ticket=0
卖票:ticket=-1
出现了-1,所以就引出同步代码块
【同步代码块】
synchronized(同步对象){需要同步的代码}
范例:
package test2; class MyThread11 implements Runnable { private int ticket = 5; public void run() { for (int i = 0; i < 100; i++) { synchronized (this) { if (ticket > 0) { try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO: handle exception e.printStackTrace(); } System.out.println("卖票:ticket=" + ticket--); } } } } } public class SyncDemo01 { public static void main(String[] args) { MyThread11 mt = new MyThread11(); Thread t1 = new Thread(mt); Thread t2 = new Thread(mt); Thread t3 = new Thread(mt); t1.start(); t2.start(); t3.start(); } }
结果:
卖票:ticket=5
卖票:ticket=4
卖票:ticket=3
卖票:ticket=2
卖票:ticket=1
这样就可以避免买票出现负数的问题!!!
还有一个方法是同步方法:
【同步方法】
synchronized 方法返回值 方法名称(参数列表){}
package test2; class MyThread11 implements Runnable { private int ticket = 5; public void run() { for (int i = 0; i < 100; i++) { this.sale1(); } } public synchronized void sale1() { if (ticket > 0) { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("卖票:ticket=" + ticket--); } } } public class SyncDemo01 { public static void main(String[] args) { MyThread11 mt = new MyThread11(); Thread t1 = new Thread(mt); Thread t2 = new Thread(mt); Thread t3 = new Thread(mt); t1.start(); t2.start(); t3.start(); } }
结果:
卖票:ticket=5
卖票:ticket=4
卖票:ticket=3
卖票:ticket=2
卖票:ticket=1