第一章 Single Threaded Execution

来源:互联网 发布:php curl 大文件 编辑:程序博客网 时间:2024/04/30 23:14

背景介绍:只允许一个线程执行

public class Gate {    private int counter = 0;    private String name = "Nobody";    private String address = "Nowhere";    public synchronized void pass(String name, String address) {        this.counter++;        this.name = name;        this.address = address;        check();    }    public synchronized String toString() {        return "No." + counter + ": " + name + ", " + address;    }   //此时check只有pass调用,且为私有,为线程安全    private void check() {        if (name.charAt(0) != address.charAt(0)) {            System.out.println("***** BROKEN ***** " + toString());        }    }}


x.iSyncA() 和 y.iSyncA(),允许一个以上线程同时执行(打印出的时间相同)x.iSyncA() 和 x.iSyncB() 相同实例的同步方法,一次只能由一个线程执行(打印出的时间不同)x.cSyncA() 和 y.cSyncA() 都是类方法,一次只能由一个线程执行测试:import java.text.SimpleDateFormat;import java.util.Date;class Something{public  static synchronized void syncA(){SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    String time=sdf.format(new Date());    System.out.println(Thread.currentThread().getName()+" say A :"+"  execute time is "+time);    try{ Thread.sleep(1000);}     catch(Exception e){e.printStackTrace();}}public  synchronized void syncB(){SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");    String time=sdf.format(new Date());    System.out.println(Thread.currentThread().getName()+" say B :"+"  execute time is "+time);    try{ Thread.sleep(1000);}     catch(Exception e){e.printStackTrace();}}}class MyThread extends Thread{private Something sth;public MyThread(Something sth) {super();this.sth = sth;}public void run(){sth.syncA();}}class CopyMyThread extends Thread{private Something sth;public CopyMyThread(Something sth) {super();this.sth = sth;}public void run(){sth.syncB();}}public class Demo02 {public static void main(String[] args) {// TODO Auto-generated method stubSomething s1= new Something();Something s2= new Something();MyThread m1= new MyThread(s1);//CopyMyThread m2= new CopyMyThread(s1);MyThread m2= new MyThread(s2);m1.start();m2.start();}}

0 0
原创粉丝点击