java线程

来源:互联网 发布:迅雷水晶矿场软件 编辑:程序博客网 时间:2024/06/06 05:19


注意:sleep()不会释放锁,而wait()会


package test.kang;/*创建线程两种方式 * 1.实现Runnable接口 * 2.继承Thread类 *线程的五种状态  * 1.new 新建状态,start()方法时,线程启动,进入Runnable状态  * 2.Runnable可运行(就绪)状态 ,当线程获取了CPU,则进入Running状态执行run方法 * 3.Running运行状态,调用yield()方法,可以使线程由Running状态进入Runnable状态 , * 线程调用了sleep()方法,会进入阻塞状态:interrupt()可以打断睡眠 * 控制台输入也会阻塞,io的socket那里也有阻塞方法 * 4.Block阻塞状态,阻塞结束时,该线程将进入Runnable状态,而非直接进入Running状态 * 5.Dead死亡状态,当线程的run()方法执行结束,线程进入Dead状态  *  * join()立即获得执行 * Thread.interrupted();被唤醒线程会出现中断异常  * Thread.yield();使线程由Running状态进入Runnable状态, 由cpu重新分配 * Thread.sleep(times); * Thread.currentThread(); 获取当前线程 * setPriority(Thread.MAX_PRIORITY); 设置线程的优先级(1~10) * t1.setDaemon(true); 设置守护线程,Java进程在全部前台线程结束时结束,而守护线程会被”提前杀掉“  * */public class Test17_Thread {public static void main(String[] args) throws InterruptedException {//继承Thread类Thread th1=new Thread(){//匿名子类public void run (){for(int i=0;i<100;i++){System.out.println("继承Thread线程方法"+i);if(i==65){try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}}}}};th1.start();//实现Runnable接口Runnable r=new Runnable(){//匿名实现类public void run (){for(int i=0;i<100;i++){System.out.println("实现Runnable线程方法"+i);if(i==65){try {Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}}}}} ;Thread th2=new Thread(r);th2.start();for(int i=0;i<100;i++){System.out.println("main主线程方法"+i);if(i==65){Thread.yield();}}}}


原创粉丝点击