1.多线程+同步机制
package cn.itcast.crawler.test;
public class ThreadTest extends Thread {
//构造方法给线程起名字
public ThreadTest(String name){
super(name);
}
//30张票
static int ticket=30;
static Object ob="a";
int i=0;
public void run() {
while(ticket>0){
if(ticket==1 || ticket==2 || ticket==3){
i=ticket;
}else{
i=(int)(Math.random()*3+1);
}
//使用同步方法,只有一个线程能运行,锁住对象,
synchronized (ob) {
if (ticket> 0) {
System.out.println(getName() +"卖出"+ i+"张票"+",还剩"+(ticket-i)+"张票");
ticket=ticket-i;
}else {
System.out.println("票卖完了");
}
//休眠1秒
try {
sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
测试类
package cn.itcast.crawler.test;
public class Test {
public static void main(String[] args) {
ThreadTest threadTest=new ThreadTest("窗口1");
ThreadTest threadTest1=new ThreadTest("窗口2");
ThreadTest threadTest2=new ThreadTest("窗口3");
threadTest.start();
threadTest1.start();
threadTest2.start();
}
}
运行结果