通过Runnable 实现run接口实现多线程
package com.xinjue.test;
/**
* Runnable 用法 和加锁的方式
* @author Administrator
*
*/
class MyThread1 implements Runnable{
private int a =10;
public void run(){
for(int i = 0; i<500; i++){
synchronized (this) { //票数上万就可以看到实际的作用范围 可以通过设置 a的值来看实际的效果
if(this.a>0){
System.out.println(Thread.currentThread().getName() + "卖票---->" + (this.a--));
}
}
}
/*while (a >0) {
synchronized (ob) { //票数上万就可以看到实际的作用范围 可以通过设置 a的值来看实际的效果
if(a>0){
System.out.println(Thread.currentThread().getName() + "卖票---->" + a);
a--;
} else {
System.out.println(Thread.currentThread().getName() + "票卖完了!");
}
}
}*/
}
}
public class Runnable_ {
public static void main(String[] args) {
// 设计三个线程
MyThread1 mt = new MyThread1();
Thread t1 = new Thread(mt, "1号窗口");
Thread t2 = new Thread(mt, "2号窗口");
Thread t3 = new Thread(mt, "3号窗口");
t1.start();
t2.start();
t3.start();
}
}