看郭克华老师的视频教学笔记(二)

理解进程和线程的概念:进程表示一个任务执行的全部过程 如播放器播放音乐,线程是在共享线程资源的条件下处理多个任务 比如上面的播放音乐的时候 会出字幕,出声音 这些细节的线程

实现线程 Thread 下的run() 方法.

 class ProcessThread extends Thread{

    int i;

    public run(){

       while(true){

             System.out.println(i);

            i--;

         }

}

}

调用 Thread th = new ProcessThread()

th.start();

Thread th1 = new ProcessThread();

th1.start()

 线程里的i 变量是分别打印的 不是共享 如果采用方法2.

class ProcessRunnable extends Runnable

{

    

       while(true){

             System.out.println(i);

            i--;

         }

}

引用

Runnable runnable = new ProessRunnable();

Thread th = new Thread(runnable);

Thread th1 = new Thread(runnable);

th.start();

th1.start();

其中的变量i 是共享的

 线程安全性的问题

  1.线程协作(join)

   class ThreadAnth extends Thread

{

          while(true){

              for( int i=0;i<1000;i++)

              {

                 sum+=i;

               }

          }

}

main(){

private ThreadAnth th= new ThreadAnt();

th.start();

//System.out.println( "结果是:"+sum);     线程并不打印出真正的结果 说明线程还没有执行完毕

System.out.println("线程等待的时候也能被执行");

try{

    th.join();

}catch(Excception ex){}

System.out.println( "结果是:"+sum);     线程能打印出真正的结果 说明线程一直在等待join 完毕

2.线程同步 synchronized

     当2个线程在同时使用一个变量的时候出现资源暂用的同时也被另外一个线程抢占 导致整个方法里的程序执行错误 这个时候需要用到 synchroniazed setTicket() 修饰符在加锁 保证整个方法里的东西执行完后 另外一个线程才能去抢占资源

 

 

        

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值