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条)

报告相同问题?

悬赏问题

  • ¥15 C# iMobileDevice
  • ¥15 谁会做这个啊#ensp#Boson NetSim
  • ¥15 如何编写针对TPS6503320FRGE型号的电源管理芯片的编程代码?
  • ¥15 设计简单目录管理系统,要满足以下内容
  • ¥15 关于九十度混合耦合器信号分析问题
  • ¥15 Cesm如何关闭不用的模块呢
  • ¥15 vue2两层数据导出为excle
  • ¥15 有人能帮我做一下这个项目吗
  • ¥15 网络上传速率比下载速率高
  • ¥15 (标签-游戏|关键词-网页游戏)