Java中同步
解决资源共享的同步操作,有两种方法:一是同步代码块,二是同步方法。
在需要同步的代码块加上synchronized关键字,
同步代码块时必须指定一个需要同步的对象,但一般都是将当前对象(this)设置成同步对象。
class Thread8 implements Runnable{ private int ticket = 5; public void run(){ for(int i=0; i<100; i++){ synchronized (this) { if(ticket>0){ try { Thread.sleep(300); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } System.out.println("买票: ticket = "+ticket--); } } } } } public class SyncDemo { public static void main(String[] args) { // TODO Auto-generated method stub Thread8 tt = new Thread8(); Thread t1 = new Thread(tt); Thread t2 = new Thread(tt); Thread t3 = new Thread(tt); t1.start(); t2.start(); t3.start(); } }
同步方法使用synchronized关键字将一个方法声明成同步方法。格式如下:
class Thread9 implements Runnable{ private int ticket = 5; @Override public void run() { // TODO Auto-generated method stub for(int i = 0; i<100; i++){ this.sale(); } } public synchronized void sale(){ if (ticket>0) { try { Thread.sleep(300); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } System.out.println("买票: ticket = "+ ticket--); } } } public class SyncDemo02 { public static void main(String[] args) { // TODO Auto-generated method stub Thread9 tt = new Thread9(); Thread t1 = new Thread(tt); Thread t2 = new Thread(tt); Thread t3 = new Thread(tt); t1.start(); t2.start(); t3.start(); } }