- //定义一个多线程测试类
- public class ThreadTest3 {
- public static void main(String[] args) {
- Runnable r=new Run();
- Thread th1=new Thread(r,"lisi");
- Thread th2=new Thread(r,"wangwu");
- Thread th3=new Thread(r,"zhaowu");
- th1.start();
- th2.start();
- th3.start();
- }
- }
- //定义一个类,实现Runnable接口,去覆盖run()方法
- class Run implements Runnable{
- private static int tk=100;
- Object obj=new Object();
- public void run(){
- while(true){
- synchronized(obj){
- if(tk>0){
- try {Thread.sleep(10);}
- catch (InterruptedException e) {}
- System.out.println("我买到了火车票,票号是"+Thread.currentThread()+tk--);
- }
-
- }
- }
-
- }
- }
复制代码 |