1、秒杀商品
代码示例:
首先,写任务类(即线程类) - MyTask
package com.zhoulz.demo05;
/**
* 任务类:
* 包含了商品数量,客户名称,送手机的行为。
*/
public class MyTask implements Runnable {
// 设计一个变量,用于表示商品的数量
private static int id = 10;
// 表示客户名称的变量
private String userName;
// run()方法不能传参数,则需要通过构造方法
public MyTask(String userName) {
this.userName = userName;
}
@Override
public void run() {
String name = Thread.currentThread().getName();
System.out.println(userName + "正在使用" + name + "参与秒杀任务。。。");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (MyTask.class){
if(id > 0){
System.out.println(userName + "使用" + name + "秒杀:" + id-- + "号商品成功啦!");
}else {
System.out.println(userName + "使用" + name + "秒杀失败啦!");
}
}
}
}
然后,写测试类 - MyTest,即主程序类,来测试任务类 :
package com.zhoulz.demo05;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* 主程序类,测试任务类。
*/
public class MyTest {
public static void main(String[] args) {
// 1、创建一个线程池对象
ThreadPoolExecutor pool = new ThreadPoolExecutor(3,5,1, TimeUnit.MINUTES,new LinkedBlockingQueue<>(15));
// 2、循环创建任务对象
for (int i = 1; i <= 20; i++) {
MyTask myTask = new MyTask("客户"+i);
pool.submit(myTask);
}
// 3、关闭线程池
pool.shutdown();
}
}
2、取款业务
代码示例:
同上,先写任务类(即线程类) - MyTask :
package com.zhoulz.demo06;
/**
* @auther zhoulz
* @description: com.zhoulz
*/
public class MyTask implements Runnable {
// 用户姓名
private String userName;
// 取款金额
private double money;
// 总金额
private static double total = 1000;
public MyTask(String userName, double money) {
this.userName = userName;
this.money = money;
}
@Override
public void run() {
String name = Thread.currentThread().getName();
System.out.println(userName+"正在准备使用"+name+"取款:"+money+"元。。。");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (MyTask.class){
if (total-money>0){
System.out.println(userName+"使用"+name+"取款:"+money+"元成功,余额:"+(total-money));
total -= money;
}else {
System.out.println(userName+"使用"+name+"取款:"+money+"元失败,余额:"+total);
}
}
}
}
然后,写测试类 - MyTest,即主程序类,来测试任务类 :
package com.zhoulz.demo06;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
/**
* @auther zhoulz
* @description: com.zhoulz
*/
public class MyTest {
public static void main(String[] args) {
// 1、创建线程池对象
ExecutorService pool = Executors.newFixedThreadPool(2, new ThreadFactory() {
int id = 1;
@Override
public Thread newThread(Runnable r) {
return new Thread(r,"ATM"+id++);
}
});
// 2、创建两个任务并提交
for (int i =1;i <= 2; i++){
MyTask myTask = new MyTask("客户" + i, 800);
pool.submit(myTask);
}
// 3、关闭线程池
pool.shutdown();
}
}