java多线程及线程池

         本文所讲的是java多线程的一些基本用法及java线程池使用的基本方法,博主也是边学边总结,有不对之处,请大家指出。

    1.java多线程的基本实现方式。

       a.继承thread类

       b.实现Runnable接口

    不废话先搬两个例子:

       方式一:继承thread类

     public static void main(String[] args) {
          SubThread st=new SubThread();
          st.setPriority(Thread.MAX_PRIORITY);
          st.start();
          for(int i=0;i<=100;i++){
             System.out.println(i+Thread.currentThread().getName());
          }
         System.out.println(st.isAlive());
        }
     }


    class SubThread extends Thread{
           public void run(){
              for(int i=0;i<=100;i++){
                 System.out.println(i+Thread.currentThread().getName());
             }
      }
   }

     方式二:实现Runnable接口

public class TestThread2 {
public static void main(String[] args) {
       SubThread1 subThread1=new SubThread1();
           Thread t=new Thread(subThread1);
           t.start();
          Thread t2=new Thread(subThread1);
           t2.start();
     }
    }


    class SubThread1 implements Runnable{
         public void run() {
            for(int i=0;i<100;i++){
            System.out.println(Thread.currentThread().getName()+"-----"+i);
         }
       }
     }

 

说明:
上述两种实现方式了run()方法,这是java多线程的一种约定。不同之处在于实现Runnable方法需要先通过Thread类的构造方法Thread(Runnable target) 构造出对象,
然后调用Thread对象的start()方法来运行多线程代码。再说一句从本身来说thread也实现了Runnable接口这个可以从thread源码里看出来。

 



实现多线程两种方式的区别:

   实现runnable接口适合资源共享,而继承thread类不适合资源共享。


这句话怎么理解呢,按照我自己的理解,是因为继承thread类实现多线程需要实例化多个线程对象,而实现runnable接口只需要实例化一个线程对象。
这一点从上述的代码中也能很好的看出来。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值