java线程互斥实例

来源:互联网 发布:网络时时音频监 编辑:程序博客网 时间:2024/05/15 13:40
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package syndemo;
class MyThread implements Runnable{

private int target=10;

        //不加synchronized时

、    /*结果:

       当前的进程t2 剩余票数:9
       当前的进程t1 剩余票数:10
       当前的进程t2 剩余票数:8
       当前的进程t1 剩余票数:7
       当前的进程t2 剩余票数:6
       当前的进程t1 剩余票数:5
       当前的进程t2 剩余票数:4
       当前的进程t1 剩余票数:3
       当前的进程t2 剩余票数:2
       当前的进程t1 剩余票数:1

       */

        public synchronized void sul(){
if(target>0){
System.out.println("当前的进程"+Thread.currentThread().getName()+" 剩余票数:"+(target--));
}

        }

public void run(){
for(int i=0;i<10;i++){
                            try{
Thread.sleep(500);
}catch(InterruptedException e){}
                            this.sul();
}
}
}

public class SynDemo{
public static void main (String[] args){
MyThread mt = new MyThread();
Thread t1 = new Thread(mt);
t1.setName("t1");
Thread t2 = new Thread(mt);
t2.setName("t2");
                t1.start();
t2.start();
}
}
原创粉丝点击