public class TestThread {
public static void main(String[] args){
System.out.println("线程执行之前!");
Thread thread1=new Thread(new MyRunnable(),"线程1");
thread1.start();
synchronized(thread1){
try {
System.out.println("线程1进入wait()");
thread1.wait();//立即释放对象锁,让另一个同步块执行
System.out.println("线程1已经进入wait()");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("线程执行之后!");
}}class MyRunnable implements Runnable{
public void run(){
synchronized(this){
for(int i=0;i<5;i++){
if(count>0){
System.out.println(Thread.currentThread().getName()+"count的值为:"+count--);
try{
System.out.println("线程进入notify()之前");
this.notify();
System.out.println("线程进入notify()之后");
}catch(Exception e){
e.printStackTrace();
}
}
}
}
}
private static int count=5;
}代码执行后结果如下:线程执行之前!
线程1进入wait()
线程1count的值为:5
线程进入notify()之前
线程进入notify()之后
线程1count的值为:4
线程进入notify()之前
线程进入notify()之后
线程1count的值为:3
线程进入notify()之前
线程进入notify()之后
线程1count的值为:2
线程进入notify()之前
线程进入notify()之后
线程1count的值为:1
线程进入notify()之前
线程进入notify()之后
线程1已经进入wait()
线程执行之后!请问调用了notify()之后不是就已经唤醒了最初的那个同步块吗,然而 "线程1已经进入wait()" 这句在最后才执行,各位求教啊
多线程javathread
for(int i=0;i<5;i++){
synchronized(lock){
1、不是用一把锁 thread1 不是 MyRunnable 自然和this不是一把锁
2、锁在循环外 循环执行完了 主线程才有执行权
3、cpu给线程的也是时间片 在时间片内thread1已经结束了看不出效果 需要给出 Thread.yield();
修正后代码public class TestThread {
public static void main(String[] args){
System.out.println("线程执行之前!");
MyRunnable my = new MyRunnable();
Thread thread1=new Thread(my,"线程1");
thread1.start();
synchronized(my){ //my与this才是一把锁
try {
System.out.println("线程1进入wait()");
my.wait();//立即释放对象锁,让另一个同步块执行
System.out.println("线程1已经进入wait()");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("线程执行之后!");
}}class MyRunnable implements Runnable{
public void run(){
for(int i=0;i<5;i++) //循环在锁外面
{
synchronized(this) //同理锁在循环里面
{
if(count>0){
System.out.println(Thread.currentThread().getName()+"count的值为:"+count--);
try{
System.out.println("线程进入notify()之前");
this.notify();
System.out.println("线程进入notify()之后");
}catch(Exception e){
e.printStackTrace();
}
}
Thread.yield(); //防止cpu不给主线程执行权
}
}
}
private static int count=5;
}