码迷,mamicode.com
首页 > 编程语言 > 详细

多线程日记(17.5.4)

时间:2017-05-04 20:14:54      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:运行   log   无线   new   logs   线程   running   pre   cpu   

 

1.线程的等待与唤醒wait()和notify();

public class Test{
    public static void main(String[]args){
        Thread thread1=new NewThread("t1");
        synchronized(thread1){
            System.out.println(Thread.currentThread().getName()+" is running");
            thread1.start();
            System.out.println(Thread.currentThread().getName()+" is running");
            try{
                thread1.wait();
                System.out.println(Thread.currentThread().getName()+" is running");
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}
class NewThread extends Thread{
    public NewThread(String name){
        super(name);
    }
    public void run(){
        synchronized(this){
            System.out.println(Thread.currentThread().getName()+":"+"notify");
            this.notify();
        }
    }
}

线程thread1是在main这个主线程上创建的,所以一开始运行的时主线程main,当thread1调用start方法,处于就绪状态,直到main被阻塞,cpu允许threadd1执行,会输出thread1:notify,直到thread1调用wait()方法被进行无线等待,最后main()进行运行。

如下程序:main运行→thread1调用start()方法运行→然后让thread1调用wait()方法进行等待→主线程main运行.

public class Test{
    public static void main(String[]args){
        Thread thread1=new NewThread("t1");
        synchronized(thread1){
            try{
                System.out.println(Thread.currentThread().getName()+":"+"running");
                //start thread1
                thread1.start();
                //thread1 wait
                thread1.wait(10000);
                System.out.println(Thread.currentThread().getName()+":"+"running");
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}
class NewThread extends Thread{
    public NewThread(String name){
        super(name);
    }
    public void run(){
        synchronized(this){
            System.out.println(Thread.currentThread().getName()+":"+"running");
        }
    }
}

多线程日记(17.5.4)

标签:运行   log   无线   new   logs   线程   running   pre   cpu   

原文地址:http://www.cnblogs.com/levi-ji/p/6808600.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!