黑马程序员-线程Thread类和Runnable接口

来源:互联网 发布:手机打碟机软件 编辑:程序博客网 时间:2024/06/05 19:58

--------------------------Android培训                   Java培训 期待与您的交流!-------------------------

/*  构造线程体的两种方式      1.继承Thread类并覆盖它的run方法。      2.实现Runnable接口并实现它的run方法。    里面有抽象方法run  其实Thread这个线程类实现了Runnable接口的*/<pre name="code" class="java">class ThreadDemo extends Thread{                    //通过继承Thread类并覆盖run方法    public ThreadDemo(String name){        super(name);    }    public void run(){                                    //覆盖父类的run方法        for (int i = 0; i < 5; i++) {            System.out.println(getName() + ":" + i);            try {                Thread.sleep((int)(Math.random()*100));//让线程睡眠,每次的输出都睡眠不超过1秒            } catch (InterruptedException e){}        }        System.out.println(getName() + "结束" );    }    public static void main(String args []){        Thread t1=new ThreadDemo("线程A");                //创建线程并启动执行        Thread t2=new ThreadDemo("线程B");        t1.start();                                        //只有获得了CPU时间片才会执行run方法        t2.start();    }}class RunnableDemo implements Runnable{        //实现Runnable接口创建线程    public void run(){                                //实现接口的方法        for (int i = 0; i < 5; i++) {            System.out.println(Thread.currentThread().getName() + ":" + i);            try {                Thread.sleep((int)(Math.random()*1000));//每次的输出都睡眠不超过1秒            } catch (InterruptedException e){}        }        System.out.println(Thread.currentThread().getName() + "结束" );    }    public static void main(String args []){        //实现继承接口runnable,创建线程的方法,*线程的创建必须是Thread ??=new Thread||继承Thread的类        RunnableDemo target=new RunnableDemo();        Thread t1=new Thread(target, "线程A");        Thread t2=new Thread(target,"线程B");        //RunnableDemo t=new RunnableDemo();t不存在start方法。        t1.start();        t2.start();            }}public class MainThreadDemo {    public static void main(String args []){        Thread t=Thread.currentThread();//返回当前线程对象        System.out.println(t);        System.out.println(t.getName());        t.setName("MainThread");        System.out.println(t);        System.out.println(t.getThreadGroup().getName());    }}

/* 线程的状态分析 1.new: 处于这个状态的线程,还没有启动。 2.runnable: 正在JVM里面执行。 3.blocked: 处于这种状态的线程正在等待监视器锁,以访问某一个对象。 4.waiting 正在无限制的等待另一个线程执行某个特定的工作。 5.timed_waiting 等待睡眠指定时间。 6.terminated 线程已经退出。 1.新建状态 2.可运行状态 3.阻塞状态 4.等待状态 5.结束状态 线程的优先级: 线程的优先级取值为 1~10的整数,优先级越大优先级越高。 优先级常量: 优先级 MIN_PRIORITY -----> 1 NORM_PRIORITY -----> 5 MAX_PRIORITY -----> 10*/public class ThreadPriorityDemo { //关于优先级的实验    //static 嵌套类    static class CounterThread extends Thread{        public CounterThread(String name){            super(name);        }        public void run(){            int count=0;            while(true){            if(count==1000000000) {    System.out.println(getName() + "结束" ); break;}//线程运行10亿次            if(count%10000000==0) {System.out.println(getName()+":"+count);           //每一千万比较一个当前线程进度            System.out.println("\n");            }count++;            }        }    }    public static void main(String args []){        CounterThread t1=new CounterThread("线程A");        CounterThread t2=new CounterThread("线程B");        CounterThread t3=new CounterThread("线程C");        //设置线程的优先等级,数值越大,等级越高,获得CPU的时间片越多                t1.setPriority(1);        t3.setPriority(5);        t2.setPriority(10);            //理论上线程B比线程A先结束        t2.start();        t3.start();        t1.start();        }}/* 通常,控制线程的结束是在线程体中通过一个循环结束的。 如果线程的run方法是一个确定次数的循环,则循环结束后,线程运行就结束了,线程进入终止状态。 也可以通过在run里面设置一个标识变量 注意的是,当线程处与终止状态,不能再调用这个线程的任何方法。*/
import java.util.Date;
public class ThreadStop {
    static class Mytimer implements Runnable{ //静态内部类
        boolean flag=true;                    //定义一个标志变量
        public void run(){
            while(flag){                    //通过flag变量控制线程结束
                System.out.println(""+new Date()+"....");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {}
            }
            System.out.println(""+Thread.currentThread().getName()+"结束");
        }
        public void stopRun(){
            flag=false;                        //将标志量变成false
        }
    }                                        //内部类结束
    public static void main(String args []){
        Mytimer timer=new Mytimer();
        Thread t=new Thread(timer);
        t.setName("Timer");
        t.start();
        for (int i = 0; i < 20; i++) {
            System.out.println(""+i);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // TODO: handle exception
            }
        }
        timer.stopRun();                //用户线程结束
    }
}




0 0