标签:
class MyThread implements Runnable{ //多个线程访问同一资源时,必须要考虑同步 //synchronized实现同步,当一个线程调用这个方法时,其他的线程是无法调用的 //线程同步(安全,但性能不高);不加synchronized是异步(不安全,但性能高) //如果有太多同步操作,可能会产生死锁 int ticket = 100; @Override public void run() { for(int i=0;i<100;i++) { synchronized(this) {//synchronized定义在代码块上 if(ticket>0) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"卖了一张, 还剩: "+(--ticket)); } } // this.sale(); } } //或者把synchronized定义在方法上,实现线程同步 public synchronized void sale() { if(ticket>0) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"卖了一张, 还剩:"+--ticket); } } } public class Demo { public static void main(String[] args) { MyThread run = new MyThread(); Thread thread1 = new Thread(run,"A"); Thread thread2 = new Thread(run,"B"); Thread thread3 = new Thread(run,"C"); thread1.start(); thread2.start(); thread3.start(); } }
标签:
原文地址:http://www.cnblogs.com/wwzyy/p/5533603.html