收藏 (0) +1 (0) +1 (0) +1
收藏成功查看收藏>>

正在阅读:攻克学习多线程时碰到的难题攻克学习多线程时碰到的难题

2004-03-26 10:05 出处:PConline 作者:qlampskyface 责任编辑:linjixiong

    public class Test implements Runnable{
      Thread thread1;
      Thread thread2;
      public Test(){
        thread1 = new Thread(this,"1");
        thread2 = new Thread(this,"2");
      }
      public static void main(String args[]){
        Test t = new Test();
        t.startThreads();
      }
      public void run(){
        //do thread's things
      }
      public void startThreads(){
        thread1.start();
        thread2.start();
      }
    }

    两种创建方式差别不大,第一种因为继承自Thread,只创建了自身对象,第二种还得创建Thread对象.但是当你想继承某一其它类时,你只能用后一种方式.大多数人偏爱后一种的原因大概也在于此吧.

-------------------------

    下面我们来讲synchronized的4种用法吧:

    1.方法声明时使用,放在范围操作符(public等)之后,返回类型声明(void等)之前.这时,线程获得的是成员锁,即一次只能有一个线程进入该方法,其他线程要想在此时调用该方法,只能排队等候,当前线程(就是在synchronized方法内部的线程)执行完该方法后,别的线程才能进入.
 
      例如:

      public synchronized void synMethod() {
        //方法体
      }

    2.对某一代码块使用,synchronized后跟括号,括号里是变量,这样,一次只有一个线程进入该代码块.此时,线程获得的是成员锁.例如:

 


 

察看评论详细内容 我要发表评论
作者笔名简短内容 发表时间
:

键盘也能翻页,试试“← →”键

相关文章

关注我们

最新资讯离线随时看 聊天吐槽赢奖品
手机访问回到顶部