1.sleep() 和 wait()的异同?
- 1.相同点:一旦执行方法,都可以使得当前的线程进入阻塞状态。
- 不同点:1)两个方法声明的位置不同:Thread类中声明sleep() , Object类中声明wait()
2)调用的要求不同:sleep()可以在任何需要的场景下调用。 wait()必须使用在同步代码块或同步方法中
3)关于是否释放同步监视器:如果两个方法都使用在同步代码块或同步方法中,sleep()不会释放锁,wait()会释放锁。
2.使用两个线程打印 1-100。线程1, 线程2 交替打印
public class CommTest {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
Thread t1 = new Thread(thread1);
Thread t2 = new Thread(thread1);
t1.start();
t2.start();
}
}
class MyThread implements Runnable {
private int number = 1;
@Override
public void run() {
synchronized (this) {
while (number <= 100) {
notify();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":" + number);
number++;
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}