cainiaodebuguilu 2017-04-25 10:22 采纳率: 12.5%
浏览 1017
已采纳

java 多线程为什么锁没用?

public class ThreadsTest {

public static void main(String[] args) {
    Threads tsa=new Threads();
    Threads tss=new Threads();
    Threads tsd=new Threads();
    Threads tsf=new Threads();
    Threads tsg=new Threads();
    Thread ts1=new Thread(tsa, "线程1");
    Thread ts2=new Thread(tss, "线程2");
    Thread ts3=new Thread(tsd, "线程3");
    Thread ts4=new Thread(tsf, "线程4");
    Thread ts5=new Thread(tsg, "线程5");
    ts1.start();
    ts2.start();
    ts3.start();
    ts4.start();
    ts5.start();
}

}

package com.huadian.bean;

public class Threads implements Runnable{
private int str=5;

public Threads(int str) {
    super();
    this.str = str;
}

public Threads() {
    super();
}

@Override
public void run() {
    synchronized (Threads.class) {
        for(int i=0;i<str;i++){
            System.out.println(Thread.currentThread().getName()+"___"+i);
            if(i==3){
                try {
                    System.out.println(Thread.currentThread().getName()+"___"+"休息休息-----------------------------");
                    Thread.sleep(1000);
                //  Threads.class.notifyAll();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }
}

}

  • 写回答

6条回答 默认 最新

  • cainiaodebuguilu 2017-04-25 11:50
    关注

    package com.huadian.bean;

    public class Threads implements Runnable{
    private Integer i=5;

    public Threads(int i) {
        super();
        this.i = i;
    }
    
    public Threads() {
        super();
    }
    
    @Override
    public void run() {
            while(i>0){
                synchronized (i) {
                System.out.println(Thread.currentThread().getName()+"___"+i);
                /*加上这里的代码就有重复数
                 * if(i==3){
                    try {
                        System.out.println(Thread.currentThread().getName()+"___"+"休息休息-----------------------------"+i);
                        Thread.sleep(5000);
                    //  Threads.class.notifyAll();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }*/
                i--;
            }
    
        }
    }
    

    }
    好了

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥20 有没有人会这个东西的
  • ¥15 cfx考虑调整“enforce system memory limit”参数的设置
  • ¥30 航迹分离,航迹增强,误差分析
  • ¥15 Chrome Manifest扩展引用Ajax-hook库拦截请求失败
  • ¥15 用Ros中的Topic通讯方式控制小乌龟的速度,走矩形;编写订阅器代码
  • ¥15 LLM accuracy检测
  • ¥15 pycharm添加远程解释器报错
  • ¥15 如何让子窗口鼠标滚动独立,不要传递消息给主窗口
  • ¥15 如何能达到用ping0.cc检测成这样?如图
  • ¥15 关于#DMA固件#的问题,请各位专家解答!