关于线程的心得

进程心得
进程:
线程可以有两种实现方式:
一种是继承Thread类;另一种是实现Runable接口。
实现资源共享的时候一般利用实现Runnable接口的方式; 

实现Runnable接口比继承Thread类所具有的优势:

1):适合多个相同的程序代码的线程去处理同一个资源

2):可以避免java中的单继承的限制

3):增加程序的健壮性,代码可以被多个线程共享,代码和数据独立。

接下来看一个后台线程的例子:

eg:

public class Test implements Runnable{

public void run(){

for( int i=0;i<10;i++){

System.out.println("后台线程启动第"+i+“次”);

}

}

public  static  void  main(String[] args) {
       Test t new  Test ();
         Thread demo =  new  Thread(t,  "线程名字" );
         demo.setDaemon( true );
         demo.start();
     }

}


如果有多个线程的话:

可以设立一个主线程,设立多个后台线程

甚至可以在主线程的RUN()的实现中调用后台线程

还有可以设定线程的优先级 setPriority(8);

    查看当前线程的名字:Thread.currentThread().getName()+"运行"+i


买票系统的线程:

class  hello  implements  Runnable {
     public  void  run() {
         for ( int  i= 0 ;i< 10 ;++i){
             synchronized  ( this ) {
                 if (count> 0 ){
                     try {
                         Thread.sleep( 1000 );
                     } catch (InterruptedException e){
                         e.printStackTrace();
                     }
                     System.out.println(count--);
                 }
             }
         }
     }
 
     public  static  void  main(String[] args) {
         hello he= new  hello();
         Thread h1= new  Thread(he);
         Thread h2= new  Thread(he);
         Thread h3= new  Thread(he);
         h1.start();
         h2.start();
         h3.start();
     }
     private  int  count= 5 ;
}

【运行结果】:(每一秒输出一个结果)

5

4

3

2

1


  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值