一、sleep()方法及案例使用
public static void sleep(long millis)throws InterruptedException
public static void sleep(long millis,int nanos)throws InterruptedException
public class testSleepAndWait {
public static void main(String[] args) {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
try {
long start=System.currentTimeMillis();
Thread.sleep(2000);
long end=System.currentTimeMillis();
System.out.println("thread1运行结束,用时"+(end-start)/1000+"秒");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
long start=System.currentTimeMillis();
long end=System.currentTimeMillis();
System.out.println("thread2运行结束,用时"+(end-start)+"秒");
}
});
thread1.start();
thread2.start();
}
}
二、wait()方法及案例使用
public final void wait()throws InterruptedException
public final void wait(long timeout)throws InterruptedException
public final void wait(long timeout,int nanos)throws InterruptedException
class MyThread {
private String s="ABCDEFGH";
private static volatile int index=0;
public synchronized void printJ(String threadName) throws InterruptedException {
while (index%2==0){
this.wait();
}
if(index>=s.length()){
return;
}
System.out.println(threadName+"输出"+s.charAt(index));
index++;
this.notify();
}
public synchronized void printO(String threadName) throws InterruptedException {
while (index%2==1){
this.wait();
}
if(index>=s.length()){
return;
}
System.out.println(threadName+"输出"+s.charAt(index));
index++;
this.notify();
}
}
public class testSleepAndWait {
public static void main(String[] args) throws InterruptedException {
MyThread myThread = new MyThread();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 3; i++) {
try {
myThread.printJ(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 3; i++) {
try {
myThread.printO(Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread1.start();
thread2.start();
}
}
三、sleep()和wait()区别与联系
- 相同点
- sleep()和wait()都可以暂停正在执行点的线程。
- 不同点
- sleep()通常被用于线程的暂停执行;wait()通常用于线程之间的通信
- sleep()是Thread类的静态方法;wait()是Object类的方法
- sleep()不释放锁;wait()释放锁
- sleep()方法被调用后,当睡眠指定的时间后,线程会自动苏醒;
wait()方法被调用后,直到另一个线程调用此对象的notify()方法或notifyAll()方法,线程才会苏醒。