先看看下面这段简单的代码:class Thread1 extends Thread {
private int x = 0; //非常耗时的工作, 比如计算, 监视...
public void run() {
while (true) {
x = (x < 100) ? (x + 1) : 0;
}
}
}class Thread2 extends Thread {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + "Thread 2 is running ...");
}
}
}public class Main {
public static void main(String[] args) {
Thread1 t1 = new Thread1();
t1.run(); //t1 没有执行完毕, 就不会执行下面的代码
System.out.println("Start another thread");
Thread2 t2 = new Thread2();
t2.run();
}
}这算不算多线程程序?t1.run() 做一项非常长时间的工作, 发现 线程 t1 启动后, 如果 t1.run() 没有执行完毕, 就不会执行其他的代码
有什么方法可以一边执行 t1.run(), 一边执行其他的代码 ?
private int x = 0; //非常耗时的工作, 比如计算, 监视...
public void run() {
while (true) {
x = (x < 100) ? (x + 1) : 0;
}
}
}class Thread2 extends Thread {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + "Thread 2 is running ...");
}
}
}public class Main {
public static void main(String[] args) {
Thread1 t1 = new Thread1();
t1.run(); //t1 没有执行完毕, 就不会执行下面的代码
System.out.println("Start another thread");
Thread2 t2 = new Thread2();
t2.run();
}
}这算不算多线程程序?t1.run() 做一项非常长时间的工作, 发现 线程 t1 启动后, 如果 t1.run() 没有执行完毕, 就不会执行其他的代码
有什么方法可以一边执行 t1.run(), 一边执行其他的代码 ?
解决方案 »
- 话说现在XML怎么样了?
- java抽象方法的定义
- tomcat是服务器吗?
- 在SWING中用JMenuItem唤出JLabel,并写日期不成功。(附源代码)我急需。谢谢个位了
- 高手们必看!!!
- JPanel和Container的区别?
- 菜...鸟...问...如何使用子类对象调用已被重写的父类方法
- 这样算不算是抽象类实例化了呢
- linux系统下,我用WINE安装了普通的QQ, 没见它的图标 请问我怎么运行它?到哪里找? 我连C盘也没找到,在哪儿?在线等!!谢谢
- 急!!!怎样用JavaPrintService打印PDF文件?分不够可以再加!
- 异常求助啊
- 新手请教一个关于java文档很弱的问题,分不多了,见谅啊!
t2.run();换成t1.start();
t2.start();start方法才启动线程
run只是一个普通的方法 而不是启动线程的方法
run只是一个普通的方法 而不是启动线程的方法同意楼上~
while (true) {
x = (x < 100) ? (x + 1) : 0;
}
-------------
死循环,根本轮不到t2;加上sleep,或waite , notify
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run method).
If this thread was constructed using a separate Runnable run object, then that Runnable object's run method is called; otherwise, this method does nothing and returns.
Subclasses of Thread should override this method.
把main()里的t1.run() t2.run() 换成t1.start() t2.start()
前面的说的都没错,用start方法启动后,会产生一个新的Runnable状态的线程,新线程会自动做run里的任务. 如果直接调用run方法,则不会产生新的线程,只是在当前线程里做run任务.
把 start() 写成了 run();原来问题在于: 在 thread1 启动后, 要很久才会执行下面的代码,
我很久都看不到显示, 以为不会继续执行下面的代码了。刚果开始学习线程, 多谢各位的指点。qxbnit(蓝灵):
线程1确实是个死循环, 但是这是其中1个线程, 是会继续执行下面的代码的
你试下就知道了。
用start()t2能得到运行时间,但t1还是死在那里!一种办法:可以两个
t1:
while(true){
//do something1...
sleep(20);
}
t2:
while(true){
//do something2...
sleep(20);
}
========
t1.start();
t2.start();