synchronized详解~~~

来源:互联网 发布:公司商标起名软件 编辑:程序博客网 时间:2024/04/30 15:49

  说实话,今天的锁,学的非常的不好,有很多问题没有能够解决,脑子现在非常的乱,学了java一年了吧,头一次纠结成这个样子,连我的强力亲友团都不给力了~~~~~~~~

  不过说回来!怪物猎人方面进展还不错!虽然还是纠结在二星,但是那个大猩猩,已经无压力了!出了几件鸟人装,还镶了两个攻击珠子~~~~

  行了废话少说!上今天的笔记吧!因为今天学的比较复杂,所以笔记也比以前详细的多,不过估计这样的笔记不会很多,呵呵,谅解吧~~~

11,09,07


如果线程处在堵塞状态被中断时,则会抛异常。

实例:

TestInterrupt 包含主方法

       构建线程类 class : InterruptThreadextends Thread

  重新run();

       System.out.println(Thread.interrupted());  //清除中断标记

3、实例:

类Stack

synchronized push(){            //给临界资源加锁

}

if(  )

this.wait();  //对临界资源调用wait()方法,使当前线程阻塞,让出CPU,同时释放对临界资源加的互斥锁

this.notify(); //调用临界资源notify()方法,唤醒线程

this.notifyAll(); //把等待的线程都唤醒。

注意:wait()方法 和 notify()方法 成对使用。

4、index 用来记录栈顶位置,堆栈区域

  push();   入栈操作

  while(index==data.length)   //这个条件若是成立,则说明桟是满的

  index--;   //栈顶标识数据  -1 。

  this.notify();  //唤醒刚才有数据的线程

  synchronized   锁的标记。

5、定时器:Timer和TimerTask

(1)java.util包中的Timer和TimerTask类也可实现多线程

(2)Timer类实现的是类似闹钟的功能,也就是定时或者每隔一定时间间隔触发一次线程。

(3)TimerTask类是一个抽象类,该类实现了Runnable接口,具备多线程的能力。

(4)通过继承TimerTask类创建子类,使该子类获得多线程的能力,将需要多线程执行的代码书写在run方法内部,然后通过Timer类启动线程的执行。

实例:部分代码解析

public class TestTimer {

       publicstatic void main(String[] args) {

              Timert = new Timer();//定时器

              TimerTask1tt1 = new TimerTask1();

              t.schedule(tt1,0);//启动线程,tt1是需要启动的线程对象 。参数0表示延迟0毫秒启动该线程,即立刻启动线程

try{

                     for(inti = 0;i < 5;i++){

                            Thread.sleep(1000);

                            System.out.println("Main:"+ i);

                     }

              }catch(Exceptione){}

       }

}

schedule()方法

(1)public voidschedule(TimerTask task,Date time):该方法的作用是在到达time指定的时间或已经超过该时间时执行线程task。
Eg:Date d = new Date(2009-1900,10-1,1,10,0,0);
t. schedule(task,d);   //调用schedule()方法

(2)public voidschedule(TimerTask task, Date firstTime, long period):在时间到达firstTime开始,每隔period毫秒就启动一次task指定的线程,这种方式会重复启动线程。
Eg:Date d = new Date(2009-1900,10-1,1,10,0,0);
t. schedule(task,d,20000);   //调用schedule()方法

(3)public voidschedule(TimerTask task,long delay)在执行schedule方法delay毫秒以后启动线程task。
t.schedule(task,1000);//在执行该行启动代码1000毫秒后启动一次线程task

(4)public voidschedule(TimerTask task,long delay,long period):在执行schedule方法delay毫秒以后启动线程task,然后每隔period毫秒重复启动线程task。


原创粉丝点击