黑马程序员技术交流社区
标题:
大神们帮忙看看
[打印本页]
作者:
NO?
时间:
2014-3-29 14:31
标题:
大神们帮忙看看
我理想的结果是test is operating!和main is operating!"交错,结果感觉还是单线程的运行结果,不过main is operating!"先运行了,想知道为什么不是交错运行?求各位大神解答,
package threadtest;
class TestThreads extends Thread{
public void run(){
for(int i=0;i<=4;i++)
System.out.println("test is operating!");
}
}
public class TestThread {
public static void main(String[] args) {
new TestThreads().start();
for(int i=0;i<=4;i++){
System.out.println("main is operating!");
}
}
}
复制代码
作者:
黄晓鑫
时间:
2014-3-29 14:34
因为这是cpu自己选择执行的,你把run方法代码抽成一个函数,把main方法的代码抽成一个函数 然后在run方法写上一个死循环 调用这俩个方法 再那俩个方法加上互斥 通讯,这个就可以交错运行了
作者:
汗血黑马
时间:
2014-3-30 20:48
这应该和类加载器有关,main主函数是程序的入口,所以会先被加载进内存,执行里面的代码,执行start方法的时候才加载TestThreads类,运行线程。
作者:
╰つ
时间:
2014-3-30 22:55
你的电脑性能好了呗,cpu一刷就运行完了呗,你把循环次数搞高点,你就能看到效果了,或者在搞个sleep,让它睡一会
作者:
执笔梦
时间:
2014-3-31 11:07
循环次数有点少,搞多一点,因为类加载器会先加载main类,所以可能会先执行main中的循环.
作者:
霍振鹏
时间:
2014-3-31 12:31
这是我写的,真心觉得写的不好,不过功能实现了,,,,你可以参考下。。。
package test;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class TestThreads extends Thread{
public void run(){
for(int i=0;i<=4;i++)
{
TestThread.lock.lock();
System.out.println("test is operating!");
try {
TestThread.condition1.signal();
TestThread.condition2.await();
TestThread.lock.unlock();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class TestThread {
static Lock lock=new ReentrantLock();
static Condition condition1=lock.newCondition();
static Condition condition2=lock.newCondition();
public static void main(String[] args) throws InterruptedException {
new TestThreads().start();
for(int i=0;i<=4;i++){
lock.lock();
condition1.await();
System.out.println("main is operating!");
condition2.signal();
lock.unlock();
}
}
}
复制代码
369.png
(1.49 KB, 下载次数: 23)
下载附件
2014-3-31 12:31 上传
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2