关于多线程的demo
项目结构一直跑的线程
程序代码:
package com.xiaoa.thread; public class Mythread implements Runnable { int tickets = 100;//線程共享的成員變量 @Override public void run() { while (true) { if (tickets > 0) { System.out.println(Thread.currentThread().getName()+"卖出的第" + tickets-- + "张票"); } } }测试1,一切看似正常
程序代码:
package com.xiaoa.test; import com.xiaoa.thread.Mythread; public class ThreadTest { public static void main(String[] args) { Mythread tt = new Mythread(); Thread t1 = new Thread(tt);//構造的線程必須傳入相同的runable,才可以共享成員變量 Thread t2 = new Thread(tt); t1.setName("售票窗口1"); t2.setName("售票窗口2"); t1.start(); t2.start(); } }
小睡一会的线程
程序代码:
package com.xiaoa.thread; public class Mythread2 implements Runnable { int tickets = 100;//線程共享的成員變量 @Override public void run() { while (true) { try { Thread.currentThread().sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } if (tickets > 0) { System.out.println(Thread.currentThread().getName()+"卖出的第" + tickets-- + "张票"); } } } }测试2,发现了线程不安全的诡异问题
程序代码:
package com.xiaoa.test; import com.xiaoa.thread.Mythread2; public class ThreadTest2 { public static void main(String[] args) { Mythread2 tt = new Mythread2(); Thread t1 = new Thread(tt);//構造的線程必須傳入相同的runable,才可以共享成員變量 Thread t2 = new Thread(tt); t1.setName("售票窗口1"); t2.setName("售票窗口2"); t1.start(); t2.start(); } }
[此贴子已经被作者于2018-8-23 14:58编辑过]