import java.io.*;
import java.lang.*;
import java.util.*;
public class hehe implements Runnable{
Timer ti = new Timer();
public static void main(String args[]){
hehe he = new hehe();
Thread t1 = new Thread(he);
Thread t2 = new Thread(he);
t1.start();
t2.start();
}
public void run(){
ti.add(Thread.currentThread().getName());
}
}
public class Timer {
private static int num = 0;
public void add(String name){
synchronized(this){
num++;
try{
Thread.sleep(1);
}catch(Exception e){
return ;
}
System.out.println(name+" "+num);
}
}
}
或者是直接在方法名字的前面加上synchronized关键字