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

© huangjiawei 中级黑马   /  2015-7-14 10:36  /  336 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

如何创建java程序的线程
方式一:继承于Thread类
  1. class PrintNum extends Thread{
  2.         public void run(){
  3.                 //子线程执行的代码
  4.                 for(int i = 1;i <= 100;i++){
  5.                         if(i % 2 == 0){
  6.                                 System.out.println(Thread.currentThread().getName() + ":" + i);
  7.                         }
  8.                 }
  9.         }
  10.         public PrintNum(String name){
  11.                 super(name);
  12.         }
  13. }


  14. public class TestThread {
  15.         public static void main(String[] args) {
  16.                 PrintNum p1 = new PrintNum("线程1");
  17.                 PrintNum p2 = new PrintNum("线程2");
  18.                 p1.setPriority(Thread.MAX_PRIORITY);//10
  19.                 p2.setPriority(Thread.MIN_PRIORITY);//1
  20.                 p1.start();
  21.                 p2.start();
  22.         }
  23. }
复制代码

方式二:实现Runnable接口
  1. class SubThread implements Runnable{
  2.         public void run(){
  3.                 //子线程执行的代码
  4.                 for(int i = 1;i <= 100;i++){
  5.                         if(i % 2 == 0){
  6.                                 System.out.println(Thread.currentThread().getName() + ":" + i);
  7.                         }
  8.                 }                       
  9.         }
  10. }
  11. public class TestThread{
  12.         public static void main(String[] args){
  13.                 SubThread s = new SubThread();
  14.                 Thread t1 = new Thread(s);
  15.                 Thread t2 = new Thread(s);
  16.                
  17.                 t1.setName("线程1");
  18.                 t2.setName("线程2");
  19.                
  20.                 t1.start();
  21.                 t2.start();
  22.         }
  23. }
复制代码

两种方式的对比:联系:class Thread implements Runnable
                         比较哪个好?实现的方式较好。①解决了单继承的局限性。②如果多个线程有共享数据的话,建议使用实现方式,同时,共享
                        数据所在的类可以作为Runnable接口的实现类。
                       
                       
线程里的常用方法:start()   run()  currentThread()  getName()  setName(String name) yield() join()  sleep() isAlive()
                             getPriority()  setPriority(int i); wait()  notify() notifyAll()

1 个回复

倒序浏览
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马