多线程同步方式和技巧

1、线程建立this

方式1:重写run方法
    Thread thread = new Thread(){
        public void run(){
            //任务
        }
    }.start();spa

 方式2:实现runnable接口
    Thread thread = new  Thread(
        new Runnable(){
            public void run(){
                //任务代码
            }
        }
    ).start();线程

2、定时器
定时器:传统定时器TraditionTimer
    new Timer().schedule(new TimerTask(){    
        public void run(){
            //任务代码
        }
    },time);   对象

3、同步接口

  实现同步的方式有:①同步代码块 synchronized {须要同步的代码},②同步方法 public void synchronized method(){}资源

注意点:方法同步锁是 this,静态方法同步锁是类文件对象。同步

同步通讯几个小的知识点要点:it

    1.同步的代码片断或数据,抽出来做为资源类使用,不要写在线程里面。io

    2.判断通讯条件时,尽可能使用while而不是使用if,由于在唤醒线程时,可能有假唤醒。thread

例如一下代码:

线程代码:

资源代码:

相关文章
相关标签/搜索