javase的复习-----11

同步与死锁:

package com.itheima;
class MyThread implements Runnable{
	private int ticket =5;
	@Override
	public void run() {
		for(int i=0; i<50;i++){
			if(ticket>0){
				try {
					Thread.sleep(300);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println("买票:ticket="+ticket--);
			}
		}
	}
	
}
public class ThreadName {
	public static void main(String[] args) {
		MyThread a = new MyThread();
		Thread q = new Thread(a,"线程");//系统会自动设置线程的名字
		Thread w = new Thread(a,"线程");//系统会自动设置线程的名字
		Thread e = new Thread(a,"线程");//系统会自动设置线程的名字
		q.start();
		w.start();
		e.start();
	}
	
	
}

买票:ticket=5
买票:ticket=4
买票:ticket=3
买票:ticket=2
买票:ticket=1
买票:ticket=0
买票:ticket=-1

解决办法:同步代码块:
package com.itheima;
class MyThread implements Runnable{
	private int ticket =5;
	@Override
	public void run() {
		for(int i=0; i<50;i++){
			synchronized (this){//设置同步操作
				if(ticket>0){
					try {
						Thread.sleep(300);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println("买票:ticket="+ticket--);
				}
			}
				
		}
	}
	
}
public class ThreadName {
	public static void main(String[] args) {
		MyThread a = new MyThread();
		Thread q = new Thread(a,"线程");//系统会自动设置线程的名字
		Thread w = new Thread(a,"线程");//系统会自动设置线程的名字
		Thread e = new Thread(a,"线程");//系统会自动设置线程的名字
		q.start();
		w.start();
		e.start();
	}
	
	
}

或者直接同步方法:
package com.itheima;
class MyThread implements Runnable{
	private int ticket =5;
	@Override
	public void run() {
		for(int i=0; i<50;i++){
			this.sale();
		}
	}
	public synchronized void sale(){//设置同步操作
		if(ticket>0){
			try {
				Thread.sleep(300);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("买票:ticket="+ticket--);
		}
	}
}
public class ThreadName {
	public static void main(String[] args) {
		MyThread a = new MyThread();
		Thread q = new Thread(a,"线程");//系统会自动设置线程的名字
		Thread w = new Thread(a,"线程");//系统会自动设置线程的名字
		Thread e = new Thread(a,"线程");//系统会自动设置线程的名字
		q.start();
		w.start();
		e.start();
	}
	
	
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值