Thread Runnable

1 线程的实现方式

   extends Thread

   implements Runnble

2 线程同步

  前提:1 两个以上的线程  2 访问同一段代码块

 

   synchronized

       同步代码块

           Object obj = new Object();

          synchronized(obj ){ // 可以放任何别的对象 比如自定义一个对象或this 所有对象都有有一个内部计算器0 1

            。。。。。。。

}

 

      非静态方法同步

 public void synchronized show() {// 方法同步用的锁对象是 this

        。。。。。。。。

}

 

静态方法同步

 public static void synchronized show() {// 方法同步用的锁对象是 当前类得Class对象 比如该方法在 Person中 则是Person.class 对象

        。。。。。。。。

}

 

 

同步安全问题(资源回收问题:多个线程操作同一资源变量 count)

   实例银行存款  比如多个线程操作同一段代码块 或 方法

 

          show(){

            if( count >0 ){

               //某个线程满足条件进入 但收回资源停止 另一线程 进入并运行 count可能变为复制

               count -= 100;

      }       

 }

 

 

 

线程通信

   典型的线程通信的例子有生产者 消费者 问题

 

package com.gui.test;

 

class Res{
 String name;
 String sex;
 boolean b = false;
}

class Thread1 implements Runnable{
 Res r;
 public Thread1(Res r) {
  this.r = r;
 }
 
 @Override
 public void run() {
  // TODO Auto-generated method stub
  int flag = 0;
  while(true) {
   synchronized (r) {
    if(r.b) try {r.wait();} catch (Exception e) {}
     if(flag == 0){
      r.name = "Tom";
      r.sex = "M";
     }else {
      r.name = "Hanmeimei";
      r.sex = "F";
     }
     flag = (flag + 1)%2;
     r.b = true;
     r.notify();
   }
   
  }
 }
 
}

class Thread2 implements Runnable{
 Res r;
 public Thread2(Res r) {
  this.r = r;
 }
 
 @Override
 public void run() {
  // TODO Auto-generated method stub
  int flag = 0;
  while(true) {
   synchronized (r) {
    if(!r.b) try {r.wait();} catch (Exception e) {}
    System.out.println(r.name + "   "  + r.sex);
    r.b = false;
    r.notify();
   }
  }
 }

 
}

public class TestSyn {
 
 
 public static void main(String[] args) {
  // TODO Auto-generated method stub
   Res r = new Res();
   new Thread(new Thread1(r)).start();
   new Thread(new Thread2(r)).start();
 }

}
 

 

 线程 停止

1 设置标志位

 run() {

       

while(flag)

{

 。。。。

}

}

 

setFlag() {

     flag = false;

}

 

 

2 interrupte()

  interrupte方法会唤醒wait或sleep 线程 但是会跑出一个InterruptedException 只要捕获异常setFlag就可停止线程

 

 

setPriority(int) 设置线程优先级 cpu 命中几率变大

 

d1.jion(); // 让出资源 等待d1线程终止再接着执行

main(string[]){
     

}

 

 

线程名称 setName(String)

  作用 统一代码块中判断currentThreadName执行不同操作

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值