一、sleep的使用

 1 public class ThreadTest {
 2     public static void main(String[] args) throws InterruptedException {
 3         Object obj = new Object();
 4         MyThread mt = new MyThread(obj);
 5         mt.start();
 6         MyThread mt2 = new MyThread(obj);
 7         mt2.start();
 8     }
 9     private static class MyThread extends Thread{
10         private Object obj;
11         public MyThread(Object obj) {
12             this.obj = obj;
13         }
14         @Override
15         public void run() {
16             System.out.println(Thread.currentThread().getName() + 
17                     " synchronized之前: " + System.currentTimeMillis());
18             synchronized(obj) {
19                 System.out.println(Thread.currentThread().getName() + 
20                         " sleep之前: " + System.currentTimeMillis());
21                 try {
22                     Thread.sleep(2000);
23                 } catch (InterruptedException e) {
24                     e.printStackTrace();
25                 }
26                 System.out.println(Thread.currentThread().getName() + 
27                         " sleep之后: " + System.currentTimeMillis());
28             }
29         }
30     }
31 }
View Code

相关文章: