A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© joeywr 中级黑马   /  2015-8-22 11:21  /  241 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

代码如下:
public class TT implements  Runnable{
int num=1;
public void run() {
  try {
  System.out.println("名字"+Thread.currentThread().getName());
  num=1000;
  System.out.println("num="+num);
//m1();
} catch (Exception e) {
e.printStackTrace();
}

}

  public  void m2(){
  System.out.println(num);
  }
  public static void main(String[] args) throws Exception {
TT tt=new TT();
   Thread  thread=new Thread(tt);
   thread.start();
   tt.m2();
}

}

为什么输出的结果 每次都是
1
名字Thread-0
num=1000
上面的代码有 main 主线程 然后我又创建了线程thread 启动了线程  应该由CPU来分配随机 先执行run()和m2
为什么每次都是先执行 tt.m2()呢?

问题2
public synchronized  void run(){} 和synchronized  public  void run(){}  synchronized位置不一样 有区别吗?

5 个回复

倒序浏览
1,你可以在run方法和m2方法中加个无限循环while(true){}再试试;
2,一般情况都是访问修饰符都放在前面的,其他关键字放在后面,具体行不行还没试。
3,此处为什么要用try---catch呢?
回复 使用道具 举报
说明 thread启动慢,前面输给了主线程
但是跑的时间再长一点点后面谁能优先执行就不一定了

回复 使用道具 举报
风华正茂 来自手机 中级黑马 2015-8-22 12:16:21
板凳
进来看看
回复 使用道具 举报
以梦为马123 发表于 2015-8-22 11:43
1,你可以在run方法和m2方法中加个无限循环while(true){}再试试;
2,一般情况都是访问修饰符都放在前面的 ...

问题一:
线程 新建 --> 就绪 --> 运行、阻塞 --> 死亡。
当线程 start() 后就就续了,接着运行,同时 当它 和 主进程没有 竞争同一个资源时,就不会再次回到就绪,而是一起运行的,,
我的问题是2个 线程同时运行, 只是显示的顺序和那个线程先执行完的问题。后面看了段代码其中加了系统方法显示系统时间(单位:ms),感觉思维豁然开朗见下例:
问题二:没区别。

代码:(可运行)

public class TT implements  Runnable{
int num=1;
public void run() {
try {
//显示 当前 线程 名字  
System.out.println("名字: "+Thread.currentThread().getName());
  
//显示 当前 系统 时间
System.out.println("public void run() 时间 :"+System.currentTimeMillis());
num=1000;
System.out.println("num="+num);
//m1();
} catch (Exception e) {
e.printStackTrace();
}

}

public  void m2(){
System.out.println("num = "+num);
}
public static void main(String[] args) throws Exception {
TT tt=new TT();

//显示 当前 系统 时间
System.out.println("new TT() 时间 :"+System.currentTimeMillis());
Thread  thread=new Thread(tt);

thread.start();
//显示 当前 系统 时间
System.out.println("thread.start() 时间 :"+System.currentTimeMillis());
System.out.println();
tt.m2();
}

}

************************************************************
结果1 :

new TT() 时间 :1439030411163
thread.start() 时间 :1439030411163

num = 1
名字: Thread-0
public void run() 时间 :1439030411163
num=1000

结果 2 :

new TT() 时间 :1439030889192
thread.start() 时间 :1439030889193

num = 1
名字: Thread-0
public void run() 时间 :1439030889193
num=1000

结果3 :

new TT() 时间 :1439030952815
thread.start() 时间 :1439030952816

名字: Thread-0
public void run() 时间 :1439030952817
num=1000
num = 1
回复 使用道具 举报
才知道有好多都不会啊
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马