1.线程的同步

 使用同步代码块或者同步方法实现同步。


a.同步代码块:使用synchronized关键字定义的代码块。在进行同步的时候需要有一个同步对象,可以使用this同步当前对象。

范例:卖票程序

class MyThread implements Runnable {
	private int ticket=5;
	
	@Override
	public void run() {
		synchronized(this){
			for(int i=0;i<10;i++){
				if(this.ticket>0){
					try {
						Thread.sleep(1000);//休眠1秒
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println(Thread.currentThread().getName()+"  ticket="+this.ticket--);
				}
			}
		}
	}
}
public class test {
	public static void main(String[] args) throws Exception {
		MyThread mt = new MyThread();
		Thread mt1 = new Thread(mt,"票贩子a");
		Thread mt2 = new Thread(mt,"票贩子b");
		Thread mt3 = new Thread(mt,"票贩子c");
		mt1.start();
		mt2.start();
		mt3.start();
	}

}


 异步的操作速度要快于同步操作,但是异步的操作属于非线程的安全操作,同步的操作属于线程安全的操作。


b.同步方法:

对于同步操作,除了用于代码块定义外,也可以在方法上定于操作。

范例:

class MyThread implements Runnable {
	private int ticket=5;
	@Override
	public void run() {
			for(int i=0;i<10;i++){
				this.sale();
			}
	}
	private synchronized void sale(){ //卖票
		if(this.ticket>0){
			try {
				Thread.sleep(1000);//休眠1秒
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(Thread.currentThread().getName()+"  ticket="+this.ticket--);
		}
	}
}


2.线程的死锁

死锁是一种不确定的状态,所以死锁的出现越少越好。


.在多线程访问同一个资源时一定要考虑到数据的同步问题,同步就使用synchronized关键字定义同步代码块或者同步方法。

.程序中如果出现过多的同步那么有可能产生死锁。