您的位置:首页 > 编程语言 > Java开发

Java学习笔记——多线程(一)

2017-08-17 12:32 253 查看
(1)继承Thread类

     Java.lang包中的Thread类,是一个专门用来创建线程的类,该类中提供了线程所用到的属性和方法。我们通过创建该类的子类来实现多线程。

publicclass TestThreadextends Thread {

publicvoid run() {

for(int
i =1;i<=10;i++)

     System.out.println("子线程:"+i);

}

     public static void main(String[] args) {

TestThread
tt =new
TestThread();

tt.start();//注意,不要直接调用run方法

for(int
i =1;i<=10;i++)

     System.out.println("主线程:"+i);

     }

}

(2)实现Runnable接口

       通过实现Runnable接口,并实现接口中定义的唯一方法run(),可以创建一个线程。

public classTestThread implementsRunnable{

        public void run() {

               for(int i = 1;i<=10;i++)

     System.out.println("子线程:"+i);

        }

             public static void main(String[] args) {

                     TestThread tt = newTestThread();

                     Thread thread=newThread(tt);

                     thread.start();

    for(int i = 1;i<=10;i++)

            System.out.println("主线程:"+i);

             }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: