线程
/*
* 实现多线程的步骤
* 步骤:
* 定义类继承 Thread
* 重写 run 方法
* 把新线程要做的事写在 run 方法中
* 创建线程对象
* 开启新线程 start , 内部会自动执行 run 方法
*/
public class Demo1_Thread {
public static void main(String[] args) {
// 创建 MyThread
MyThread mt = new MyThread();
// mt.run();
mt.start();
for (int i = 0; i < 4000; i++) {
System.out.println(i);
}
}
}
public class MyThread extends Thread {
@Override
public void run() {
// 需要做的事
for (int i = 0; i < 4000; i++) {
System.out.println("mt-------" + i);
}
}
}
还有其他的方法请参看java.lang.Thread里的方法
模拟售票系统
//继承Thread
public class TicketSell extends Thread {
// 成员变量 票
static int num = 100;
public TicketSell() {
}
public TicketSell(String name) {
super(name);
}
@Override
public void run() {
// 卖票
while (true) {
//加同一把锁实现同步
synchronized (TicketSell.class) {
// 停下来
System.out.println( getName() );
//判断票数
if (num <= 0) {
break;
}
try {
//这里会引发异常,是编译时异常,需要try..catch处理,不让编译不通过,
Thread.sleep(10);
System.out.println(getName() + "正在出售第" + num-- + " 张票");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class SellDemo {
public static void main(String[] args) {
TicketSell t1 = new TicketSell("窗口1");
TicketSell t2 = new TicketSell("窗口2");
TicketSell t3 = new TicketSell("窗口3");
TicketSell t4 = new TicketSell("窗口4");
t1.start();
t2.start();
t3.start();
t4.start();
}
}