这个代码哪里有问题,调了好久- /*
- * 同步的两前提:如果不满足,同步失败;
- * 1,
- *
- * */
- package duoxiancheng;
- public class ThreadShouPiaoEx {
- public static void main(String [] x)
- {
- ShouPiao_xiTong s=new ShouPiao_xiTong();
- Thread t=new Thread(s);
- Thread t1=new Thread(s);
-
- t.start();
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- // TODO 自动生成的 catch 块
- e.printStackTrace();
- }
- s.flag=false;
- t1.start();
-
- }
-
- }
- class ShouPiao_xiTong implements Runnable {
- private int piao = 100;
-
-
- boolean flag = true;
-
- public void run() {
- if(flag==true)
- {
- while (true) {
- synchronized (this) {
- if (piao > 0) {
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- // TODO 自动生成的 catch 块
- e.printStackTrace();
- }
- System.out.println("run--"+Thread.currentThread().getName() + " "
- + piao);
- piao--;
- }
-
-
- }
- }
- }else
- {
- while(true)
- {
- run1();
- }
-
- }
-
- }
- public synchronized void run1()
- {
- if (piao > 0) {
- try {
- Thread.sleep(10);
- } catch (InterruptedException e) {
- // TODO 自动生成的 catch 块
- e.printStackTrace();
- }
- System.out.println("run1++"+Thread.currentThread().getName() + " "
- + piao);
-
- }
- piao--;
-
- }
-
- }
-
复制代码 |
|