练习一:售票
需求:
一共有1000张电影票,可以在两个窗口领取,假设每次领取的时间为3000毫秒,
请用多线程模拟卖票过程并打印剩余电影票的数量
//第一种方式实现多线程,测试类中MyThread会创建多次,所以ticket需要加static 公用
package mythreadtest.test1;
public class Mythread1 extends Thread{
static int ticket=1000;
public void run(){
//循环
while (true){
//同步代码块
synchronized (Mythread1.class){
//判断共享数据
if(ticket==0){
break;
}else{
try {
Thread.sleep(3000);
} catch (InterrupedException e) {
throw new RuntimeException(e);
}
ticket--;
System.out.println(getName()+"在买票,还剩下"+ticket+"张票!");
}
}
}
}
}
package mythreadtest.test1;
public class test1 {
public static void main(String[] args) {
Mythread1 t1=new Mythread1();
Mythread1 t2=new Mythread1();
t1.setName("窗口一");
t2.setName("窗口二");
t1.start();
t2.start();
}
}
练习二:赠送礼物
需求:
有100份礼品,两人同时发送,当剩下的礼品小于10份的时候则不再送出。
利用多线程模拟该过程并将线程的名字和礼物的剩余数量打印出来
第二种:Runnable接口实现多线程
package mythreadtest.test2;
public class Myrunnable implements Runnable{
static int cnt=100;
public void run(){
while (true){
synchronized (Myrunnable.class){
if(cnt<10){
System.out.println("礼物还剩下"+cnt+"份,不在赠送");
break;
}else{
cnt--;
System.out.println(Thread.currentThread().getName()+"在赠送礼物,还剩下"+cnt+"份");
}
}
}
}
}
package mythreadtest.test2;
public class test2 {
public static void main(String[] args) {
//创建参数对象(实现接口)
Myrunnable mr=new Myrunnable();
//创建线程对象
Thread t1=new Thread(mr,"窗口一");
Thread t2=new Thread(mr,"窗口二");
t1.start();
t2.start();
}
}
练习三:打印数字
需求:
同时开启两个线程,共同获取1-100之间的所有数字。
将输出所有的奇数。
package mythreadtest.test3;
public class Mythread extends Thread{
static int num=99;
public void run(){
while (true){
synchronized (Mythread.class){
if(num<0){
System.out.println("1-100奇数输出完毕");
break;
}else{
// try {
// Thread.sleep(500);
// } catch (InterruptedException e) {
// throw new RuntimeException(e);
// }
System.out.println(Thread.currentThread().getName()+"在输出:"+num);
num-=2;
}
}
}
}
}
package mythreadtest.test3;
public class test {
public static void main(String[] args) {
Mythread t1=new Mythread();
Mythread t2=new Mythread();
t1.setName("线程1");
t2.setName("线程2");
t1.start();
t2.start();
}
}