public class TestSy implements Runnable
{
Tim tim = new Tim();

public static void main(String[] args) 
{
TestSy f = new TestSy();
Thread f1 = new Thread(f);
Thread f2 = new Thread(f);
f1.setName("111");
f2.setName("222");
f1.start();
f2.start();



System.out.println("Hello World!");
}
public void run() {
//System.out.println("sda");
tim.add(Thread.currentThread().getName());
}
}class Tim
{
private static int num = 0;
public synchronized void add(String name) {
num ++;
try
{
Thread.sleep(1);
}
catch (InterruptedException k)
{
System.out.println(name + "你是第" + num + "个使用线程");
}
}
}

解决方案 »

  1.   

    public class TestSy implements Runnable{
    Tim tim = new Tim(); public static void main(String[] args){
    TestSy f = new TestSy();
    Thread f1 = new Thread(f);
    Thread f2 = new Thread(f);
    f1.setName("111");
    f2.setName("222");
    f1.start();
    f2.start();
    System.out.println("Hello World!");
    }
    private int i = 0 ;
    public void run(){
    while(i ++ < 100){
    tim.add(Thread.currentThread().getName());
    // Thread.currentThread().interrupt();
    }
    }
    }class Tim{
    private static int num = 0; public synchronized void add(String name){
    num++;
    try{
    Thread.sleep(100);
    System.out.println(name + "你是第" + num + "个使用num的");
    }catch(InterruptedException k){
    System.out.println("线程" + name + "被打断");
    }
    }
    }
      

  2.   

    程序本身没什么问题的。。你看不到效果是因为你的打印语句放错地方了
    把打印语句加到Thread.sleep(1000)的前面来。
    System.out.println(name + "你是第" + num + "个使用线程");
    Thread.sleep(1000);
      

  3.   

    呵呵,等到休眠后抛异常打印?你的线程正常的休眠完了,它就不会抛异常了,不抛异常catch块中的就不会执行了。
    那你想得到什么样的打印效果呢?
      

  4.   

    public class TestSy implements Runnable 

    Tim tim = new Tim();  public static void main(String[] args) 

    TestSy f = new TestSy(); 
    Thread f1 = new Thread(f); 
    Thread f2 = new Thread(f); 
    f1.setName("111"); 
    f2.setName("222"); 
    f1.start(); 
    f2.start(); 
    System.out.println("Hello World!"); 


    public void run() { 
    //System.out.println("sda"); 
    synchronized(tim){
    tim.add(Thread.currentThread().getName()); 

    }
    } class Tim 

    private static int num = 0; 
    public  void add(String name) { 
    num ++; 
    try 

    Thread.sleep(1);
    System.out.println(name + "你是第" + num + "个使用线程"); 

    catch (InterruptedException k) 

    k.printStackTrace();


    }