注册 登录
编程论坛 JAVA论坛

线程同步问题

ycl239429582 发布于 2017-11-11 20:49, 1805 次点击
public class Dome{
   public static void main (String[] args){
       Stu s=new Stu();
    Thread t1=new Thread(s,"窗口1");
    Thread t2=new Thread(s,"窗口2");
    Thread t3=new Thread(s,"窗口3");
    t1.start();
    t2.start();
    t3.start();
    }
}
class Stu implements Runnable
{
    private int i=10;
    private synchronized void fun(){
          if(i>0){
             try{Thread.sleep(100);
             }catch(Exception e){
          }
          System.out.println(Thread.currentThread().getName()+"卖票 "+i--);                        
          }
      }
    public void run(){
        while(i>0){
      
       this.fun();
       }
     }
}

结果:
窗口1卖票 10
窗口1卖票 9
窗口1卖票 8
窗口1卖票 7
窗口1卖票 6
窗口1卖票 5
窗口1卖票 4
窗口1卖票 3
窗口1卖票 2
窗口1卖票 1
                 怎么老是一号窗口 已经用了同步方法了 ,不知哪里错了,,,,,求解》。。。。。。。。。。。。。。。。。。。。。。。。。
4 回复
#2
林月儿2017-11-12 01:15
多运行几次吧,时间片分配随机
不过你这个三个线程是同一对象,同步锁有用吗?
#3
ycl2394295822017-11-12 12:30
这是我照书上写的。但运行结果老是这样。已经运行十几次了。不知道错哪里了(。ì _ í。)^ _ ^。能帮我改下代码吗  
感激不尽。!!n^ _ ^。        (^-^)
#4
林月儿2017-11-12 14:37
    Stu s=new Stu();
    Thread t1=new Thread(s,"窗口1");
    Thread t2=new Thread(s,"窗口2");
    Thread t3=new Thread(s,"窗口3");

改成三个实例呢,比如
程序代码:

Stu s1=new Stu();
Stu s2=new Stu();
Stu s3=new Stu();
Thread t1=new Thread(s1,"窗口1");
Thread t2=new Thread(s2,"窗口2");
Thread t3=new Thread(s3,"窗口3");

你是想看什么效果呢?
或者说想验证什么东西?
#5
ycl2394295822017-11-13 17:45
窗口1卖票 10
窗口2卖票 9
窗口3卖票 8
窗口3卖票 7
窗口3卖票 6
窗口1卖票 5
窗口1卖票 4
窗口2卖票 3
窗口1卖票 2
窗口1卖票 1

我想要这种效果
1