实验十一 Java多线程程序设计(二)
一、实验目的
- 掌握Java多线程程序设计方法。
二、实验内容
上机实现下列程序并观察程序的运行情况:
- 用两个线程模拟存票、售票过程。
假定开始售票处并没有票,一个线程往里存票,另外一个线程则往外卖票
新建一个票类对象,让存票和售票线程都访问它。本例采用两个线程共享同一个数据对象来实现对同一份数据的操作。
三、实验要求(必做实验,2学时)
- 掌握Java多线程的创建和使用。
- 掌握Java多线程同步技术;理解产生死锁现象的原因,学习如何避免死锁。
四、实验结果、发现和总结
package synch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @program: Java_Experiment
* @description:
* @author: SXH
* @create: 2022-04-21 11:23
**/
public class Ticket {
private Lock lock;
private Condition condition;
private int number;
public Ticket(){
number=0;
lock=new ReentrantLock();
condition= lock.newCondition();
}
public void transfer(int key,int n) throws InterruptedException{
lock.lock();
int judge=(int)Math.pow(-1,key);
try {
while(number+judge*n<0)
condition.await();
System.out.print(Thread.currentThread());
number+=judge*n;
if (judge==-1) System.out.printf(" now take %d tickets out, ",n);
else System.out.printf(" now add %d tickets, ",n);
System.out.printf("current number is: %d\n",number);
condition.signal();
}
finally {
lock.unlock();
}
}
}
import synch.Ticket;
/**
* @program: Java_Experiment
* @description: Java Experience_11 use Thread and Runnable to simulate selling tickets
* @author: SXH
* @create: 2022-04-21 10:30
**/
public class SellTickets {
public static void main(String[] args) {
var ticket=new Ticket();
Runnable t=()->{
try {
while (true) {
int key = 1;
int n = (int) (Math.random() * 10);
ticket.transfer(key, n);
Thread.sleep((int) (Math.random() * 10));
}
}
catch (InterruptedException e){
System.out.println(e.getMessage());
}
};
Runnable a=()->{
try {
while (true) {
int key = 0;
int n = (int) (Math.random() * 10);
ticket.transfer(key, n);
Thread.sleep((int) (Math.random() * 10));
}
}
catch (InterruptedException e){
System.out.println(e.getMessage());
}
};
var take=new Thread(t);
var add=new Thread(a);
take.start();
add.start();
}
}