A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 小邱 中级黑马   /  2015-4-7 22:33  /  481 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

/*
        进程:正在运行的程序。
        线程:程序中独立的控制单元,线程控制着进程的执行。
        例子:运行中的迅雷是一个进程,正在下载的任务是线程。
        (在某一时刻,只有一个线程在运行,线程是在互相交替地运行,交替时间间隔由CPU决定。)
       
        进程中的主线程:运行的代码存在于main方法的线程。
       
        线程的创建方式:继承法和实现法。
       
*/

//继承法示例:受限于单继承的局限性
class Student extends Thread
{
        public void run()//重写Runnable中的run方法
        {
                for(int x=0;x<100;x++)
                {
                        System.out.println(Thread.currentThread().getName()+"-------"+x);
                }
        }
}
class Test
{
        public static void main(String[] args)
        {
                Student stu1=new Student();
                stu1.start();
                Student stu2=new Student();
                stu2.start();
                Student stu3=new Student();
                stu3.start();
                Student stu4=new Student();
                stu4.start();
               
                //Person p=new Person();
                //p.show();
        }
}

//实现法:避免了单继承局限
class Person implements Runnable
{
        private int y=100;
        public void run()//重写Runnable中的run方法
        {
                while(true)
                {
                        if(y>0)
                                System.out.println(Thread.currentThread().getName()+"-------"+y--);
                }
        }
}
class Test2
{
        public static void main(String[] args)
        {
                Person p=new Person();
               
                Thread t1=new Thread(p);
                Thread t2=new Thread(p);
                Thread t3=new Thread(p);
                Thread t4=new Thread(p);
                t1.start();
                t2.start();
                t3.start();
                t4.start();
        }
}


0 个回复

您需要登录后才可以回帖 登录 | 加入黑马