Thread知识 (火车票到结束-项目)
package 火车票;
class Mythread implements Runnable{
private int ticket=10;
@Override
public void run() {
for (int i = 0; i < 100; i++) {
synchronized (this) {//同步代码块
if(ticket>0){//证明还有票
try {
Thread.sleep(300);//睡眠0.3秒
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println("现在一共有"+ticket);
System.out.println("剩余的票数:ticket="+ticket--);
//System.out.println("现在剩余的票数"+ticket);
if(ticket<=0){
System.out.println("票已售完!!!");
}
}
}
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
Mythread my1=new Mythread();
Thread t1=new Thread(my1);//线程一
Thread t2=new Thread(my1);//线程二
Thread t3=new Thread(my1);//线程三
t1.start();//线程的开始
t2.start();
t3.start();
}
}
第二种:
package 火车票;
class Mythread1 implements Runnable{
private int ticket=10;
@Override
public void run() {
System.out.println("现在一共有"+ticket);
for (int i = 0; i < 100; i++) {
if(ticket>0){//证明还有票
try {
Thread.sleep(300);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("卖票:ticket="+ticket--);
}
}
}
}
public class ThreadDemo1 {
public static void main(String[] args) {
Mythread1 my1=new Mythread1();
Thread t1=new Thread(my1);
t1.start();
}
}