黑马程序员技术交流社区
标题:
一段代码中的多线程问题
[打印本页]
作者:
joeywr
时间:
2015-8-22 11:21
标题:
一段代码中的多线程问题
代码如下:
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位置不一样 有区别吗?
作者:
以梦为马123
时间:
2015-8-22 11:43
1,你可以在run方法和m2方法中加个无限循环while(true){}再试试;
2,一般情况都是访问修饰符都放在前面的,其他关键字放在后面,具体行不行还没试。
3,此处为什么要用try---catch呢?
作者:
liuch111
时间:
2015-8-22 12:04
说明 thread启动慢,前面输给了主线程
但是跑的时间再长一点点后面谁能优先执行就不一定了
作者:
风华正茂
时间:
2015-8-22 12:16
进来看看
作者:
joeywr
时间:
2015-8-22 17:01
以梦为马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
作者:
收获远眺
时间:
2015-8-22 17:25
才知道有好多都不会啊
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2