62,628
社区成员
发帖
与我相关
我的任务
分享
public static void main(String[] args) {
String lock = new String();
System.out.println("开始执行main方法");
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(i);
}
}
});
thread.start();
try {
synchronized (lock) {
lock.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("main方法执行结束");
}
public static void main(String[] args) {
String lock = new String();
System.out.println("开始执行main方法");
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(i);
}
}
});
thread.start();
try {
synchronized (thread) {
thread.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("main方法执行结束");
}
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(i);
}
}
public synchronized void get() {
while (flag)
try {
wait();
} catch (Exception e) { }
flag = true;
notify();
}
public synchronized void set() {
while (!flag)
try {
wait();
} catch (Exception e) { }
flag = false;
notify();
}
/*
猜测:
r是Thread的一个对象
r.start()会将以r为监视器的线程池中的线程全部开启
实验以及结果:
实现另外两个线程,让它们在r.start()之前冻结,
全程没有使用notify方法,但是主函数线程、第二个线程、
第三个线程全都被唤醒。
但是如果让主函数线程睡眠10毫秒再等待,即主线程在r.start()后
再陷入等待状态,此时主函数不能被唤醒。
如果主函数线程设置为沉睡0毫秒后等待,主函数依旧可以被唤醒,
原因是主函数线程在r.start()之前陷入等待。
结果证实了猜测。
*/
class Demo
{
public static void main(String[] args) {
String lock = new String();
System.out.println("开始执行main方法");
final Thread r = new Thread();
Thread newThread_1 = new Thread(new Runnable(){
public void run()
{
try
{
synchronized(r)
{
System.out.println("第二个线程开启");
System.out.println("第二个线程进入等待");
r.wait();
}
}
catch (InterruptedException e)
{
}
System.out.println("第二个线程被唤醒");
}
});
Thread newThread_2 = new Thread(new Runnable(){
public void run()
{
try
{
synchronized(r)
{
System.out.println("第三个个线程开启");
System.out.println("第三个线程进入等待");
r.wait();
}
}
catch (InterruptedException e)
{
}
System.out.println("第三个线程被唤醒");
}
});
newThread_1.start();
newThread_2.start();
System.out.println("监视器线程开启");
r.start();
//让主线程沉睡10毫秒。如果沉睡0毫秒则依旧会被唤醒
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
}
//让主函数进入等待状态,观察是否会被唤醒
try
{
synchronized (r)
{
System.out.println("主线程进入等待");
r.wait();
System.out.println("主线程被唤醒");
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("main方法执行结束");
}
}
