当前位置: 移动技术网 > IT编程>开发语言>Java > 线程之间的数据共享、线程之间的通信 java

线程之间的数据共享、线程之间的通信 java

2020年07月29日  | 移动技术网IT编程  | 我要评论

用Runnable接口来模拟航班售票系统

class ThreadSale implements Runnable{
    private int ticket = 10 ;
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true){
			if(ticket > 0){
				System.out.println(Thread.currentThread().getName()+ "售票机第"+ ticket-- + "号" );
			}else
			{
				System.exit(0);
			}
		}
	}
	
}

public class app11_5 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
      ThreadSale t = new ThreadSale();
      Thread t1 = new Thread(t,"第一售票窗口");
      Thread t2 = new Thread(t,"第二售票窗口");
      Thread t3 = new Thread(t,"第三售票窗口");
      t1.start();
      t2.start();
      t3.start();

	} 

}

在JAVA中,利用互斥锁机制来实现线程之间的互斥操作

JAVA中使用synchronized关键字来标识同步的资源,实际上指的是互斥

synchronized的功能是:首先判断对象或者方法的互斥锁是否存在,如果存在,就会获得互斥锁。执行代码段,在执行代码段的期间内。其他对象不能够得到互斥锁,也就是执行不了代码段。实现了互斥的操作

//2020.7.27 飞飞飞  同步线程用户模拟取款
class bank{
	private static int sum = 2000 ;
	public synchronized static void discount(int k){
		int tem = sum ;
		tem = tem - k ;
		try{
			Thread.sleep((int)(1000*Math.random()));
		}catch(InterruptedException e){}
		System.out.println("余额为"+ tem );
		sum = tem ;
      }
}
	class Customer extends Thread{
		public void run(){
			
			for (int i = 0 ; i < 4; i++){
				bank.discount(100);
			}
		}
	}
public class app11_6 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Customer c1 = new Customer();
		Customer c2 = new Customer();
		c1.start();
		c2.start();
	}
}

用两个线程模拟存票、售票过程,要求每存入一张票,就售出一张票,售出后再存入,直至售完为止

用到了notify()函数,唤醒另一个正在等待的对象互斥锁的一个线程

wait() 函数 ,当前线程休眠,并且释放锁


public class app11_8 {

	public static void main(String[] args) {
		Tickets t = new Tickets(10);
		new Produre(t).start();
		new Consumer(t).start();
		
	}

}
 class Tickets{
	protected int size;//10
	int number = 0;
	boolean available = false;
	public Tickets(int size){
		this.size = size;
	}
	public synchronized void put(){
		//同步方法,实现存票方法
		if(available) try{wait();}  //如果有票,等待售出
		catch(Exception e){}
		//如果没票,存入票
		System.out.println("存入第【"+(++number)+"】号票");
		available = true;
		notify();//唤醒售票开使售票
	}
	public synchronized void sell(){
		//同步方法,实现售票方法
		if(!available)
			try{wait();}catch(Exception e){}
		System.out.println("售出第【"+(number)+"】号票");
		available = false;
		notify();
		if(number ==size)
			number = size+1;//执行完毕
	}
}
 class Produre extends Thread{
	 //存票线程类
	 Tickets t = null;
	 //共享票类对象
	 public Produre (Tickets t){
		 this.t = t;
		 
	 }
	 public void run(){
		 while(t.number<t.size)
			 t.put();
	 }
 }
class Consumer extends Thread{
	Tickets t = null;
	public Consumer(Tickets t){
		this.t = t;
	}
	public void run(){
		while (t.number<=t.size)
			t.sell();
	}
}

 

本文地址:https://blog.csdn.net/htthr/article/details/107609294

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网