I'm new to multiple-thread in java.I write some class to test functions of synchronized.I have some method using synchronized:
public class ShareUtil {
private static Queue<Integer> queue = new LinkedList<Integer>();
public static synchronized void do1(){
System.out.println("do1");
sleep();
}
public static synchronized void do2(){
System.out.println("do2");
sleep();
}
private static void sleep(){
try {
Thread.sleep(1000*50000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You can see there are two method using synchronized,and I run two thread to use these two methods respectively.
class Run1 implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
ShareUtil.do1();
}
}
class Run2 implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
ShareUtil.do2();
}
}
public class DoMain {
public static void main(String[] args) {
ExecutorService pools = Executors.newCachedThreadPool();
for(int i=0;i<10;i++){
pools.execute(new Run1());
pools.execute(new Run2());
}
pools.shutdown();
}
}
But,it just print "do1" not print "do2".I want to know why?the key of "synchronized" using method to make the method only one thread use at the same time,but why lock the others method?