测试:
import org.omg.Messaging.SyncScopeHelper;
public class TestThread {
public static void main(String[] args) {
Tree tree = new Tree();
tree.value = 100;
ThreadPiao t1 = new ThreadPiao("线程1",tree);
ThreadPiao t2 = new ThreadPiao("线程2",tree);
ThreadPiao t3 = new ThreadPiao("线程3",tree);
t1.start();
t2.start();
t3.start();
try {
t1.join();//这样可以使线程提前
t2.join();
t3.join();
}catch (InterruptedException e){
e.printStackTrace();
}
System.out.println("~~~~"+tree.value);
}
}
线程类,模拟售货员:
import javax.naming.Name;
public class ThreadPiao extends Thread {
private String name;
private Tree tree ;
ThreadPiao(String name, Tree tree) {
this.name = name;
this.tree = tree;
}
public void run() {// synchronized 不用锁run只锁add ,这样的好处是由于此处没加锁_节省效率,<<只锁调用资源的方法就行>>
while (tree.value!=0) {
tree.sale(name);
try {
Thread.sleep(10);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
-票
public class Tree {
int value;
public synchronized void sale(String name){
value-=1;
System.out.println(name+"--->卖了"+"第" + (100 - value) + "张");
//不是从方法内部声明的变量才需要锁
}
}