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");
t2.start();
t1.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的线程");
//}
}
}
test指向new出来的TestSync对象,在TestSync里面,作为成员变量,time引用指向新new出来的Timer对象,请问为什么会这样。
为什么Timer timer = new Timer();放在外面,
Timer timer = new Timer();
public static void main(String[] args) {
TestSync test = new TestSync();
Thread t1 = new Thread(test);就是这一部分看不懂!!!!!!!!!!
而且已第一个类来new对象也很少见,王高手指点。
------解决方案--------------------------------------------------------
整理一下可能会更易于理解:
- Java code
public class TestSync implements Runnable{ Timer timer = new Timer(); //类成员变量。 public void run() //类成员方法。 { timer.add(Thread.currentThread().getName()); } public static void main(String[] args) //程序入口。 { TestSync test = new TestSync(); //定义并初始化类TestSync的对象test. Thread t1 = new Thread(test); //创建线程对象。(用Thread类的 Thread(Runnable target)构造方法。 Thread t2 = new Thread(test); t1.setName("t1"); //设置线程名。 t2.setName("t2"); t2.start(); //启动线程。 t1.start(); }}
------解决方案--------------------------------------------------------
很好理解,没有问题,就是这种写法
Thread t1 = new Thread(test);
就是线程的一种构造方法