关于Thread的一个问题,麻烦大家帮帮忙。

iaiti
Java领域优质创作者
博客专家认证
2012-09-13 09:09:31
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对象也很少见,王高手指点。
...全文
107 2 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
阿甘1976 2012-09-13
  • 打赏
  • 举报
回复
很好理解,没有问题,就是这种写法
Thread t1 = new Thread(test);
就是线程的一种构造方法
nmyangym 2012-09-13
  • 打赏
  • 举报
回复
整理一下可能会更易于理解:


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();
}
}

62,635

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧