本帖最后由 宋超2356 于 2014-4-15 15:59 编辑
- public class TestSync implements Runnable {
- Timer timer = new Timer();
- public static void main(String[] args) {
- TestSync test = new TestSync();
- Thread t1 = new Thread(test);
- Thread t2 = new Thread(test);
- t1.setName("t1");
- t2.setName("t2");
- t1.start();
- t2.start();
- }
- public void run(){
- timer.add(Thread.currentThread().getName());
- }
- }
- class Timer{
- private static int num = 0;
- public synchronized void add(String name){
- //synchronized (this) {
- num ++;
- try {Thread.sleep(1);}
- catch (InterruptedException e) {}
- System.out.println(name+", 你是第"+num+"个使用timer的线程");
- //}
- }
- }
复制代码 类似 synchronized的用法里,如果一个方法被 synchronized修饰,但是其他方法还可以访问它里面的变量是么? |