public class TestThread extends Thread{ //定义静态变量,为所有对象所共有 private static int ticket = 50; //定义静态对象 object,保证在使用时synchronized获得对象的唯一性 //不然main方法里new多个对象就有多个锁 private static Object object = new Object(); //定义线程名称 public TestThread(String name) { super(name); } @Override public void run(){ while (true){ //这里不能用this,这里的this代表test1,test2,test3三个对象,锁不唯一 //方式一 //synchronized(object){ //方式二 //获取TestThread1的class对象,class 类名 = 类名.class,类名.class只会加载一次 synchronized(TestThread1.class){ if(ticket > 0){ try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "卖票,票号为:" + ticket); ticket--; }else{ break; } } } } public static void main(String[] args) throws Exception { TestThread test1 = new TestThread("窗口1"); TestThread test2 = new TestThread("窗口2"); TestThread test3 = new TestThread("窗口3"); test1.start(); test2.start(); test3.start(); } }第二种实现Runnable接口
public class RunnableTest { public static void main(String[] args) { MyThear1 myThear1 = new MyThear1(); Thread thread1 = new Thread(myThear1,"窗口1"); Thread thread2 = new Thread(myThear1,"窗口2"); Thread thread3 = new Thread(myThear1,"窗口3"); thread1.start(); thread2.start(); thread3.start(); } } class MyThear1 implements Runnable{ private static int ticket = 30; //方式一 保证在使用时synchronized获得对象的唯一性 Object object = new Object(); //该子类应重写 Thread 类的 run 方法 @Override public void run() { while (true){ //方式一 //synchronized(object){ //方式二 //此时的this唯一的MyThear1对象 //synchronized (this){ //方式三 获取的MyThear1的class对象 synchronized(MyThear1.class){ if (ticket > 0) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + "卖出票号:" + ticket); ticket--; } else { break; } } } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)