很抱歉,如果这是一个基本问题,但我一直在考虑做多个精灵循环,并且我第一次尝试在main中创建两个线程,两个都有while(true)循环。我的意图:让两个线程同时循环。但是,当我运行程序时,它似乎会中断执行流程,第二个循环不会在新线程中执行,而只是在程序停留在线程的第一个无限while()循环时停止。我认为它仍然只是执行主线程,而不是开始一个新线程然后继续。
我尝试过两种方式:
使用主题:
public class Zzz {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
r1 r = new r1();
r2 a = new r2();
r.start();
a.start();
}
}
public class r1 extends Thread {
@Override
public void start() {
while(true) {
System.out.println("r1");
try {
this.sleep(100);
} catch (Exception ex) {
}
}
}
}
public class r2 extends Thread {
@Override
public void start() {
while(true) {
System.out.println("r2");
try {
this.sleep(100);
} catch (Exception ex) {
}
}
}
}
一次使用Runnable:
public class Zzz {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
r1 r = new r1();
r2 a = new r2();
r.run();
a.run();
}
}
public class r1 implements Runnable {
@Override
public void run() {
while(true) {
System.out.println("r1");
try {
Thread.sleep(100);
} catch (Exception ex) {
}
}
}
}
public class r2 implements Runnable {
@Override
public void run() {
while(true) {
System.out.println("r2");
try {
Thread.sleep(100);
} catch (Exception ex) {
}
}
}
}
但无济于事。它总是卡在R1。任何人的想法?我用Google搜索并查看了有关线程的内容,我无法在任何地方找到它。
答案 0 :(得分:2)
你需要覆盖run方法&如果是runnable,你需要创建Thread的实例
public class MyThread extends Thread{
@Override
public void run() {
while(true) {
System.out.println("My Thread running");
}
}
对于Runnable
class MyRunnable implements Runnable{
public void run(){
System.out.println("I am executing by Thread: " + Thread.currentThread().getName());
}
}
和
Thread mythread = new MyThread();
mythread.setName("T1");
Thread myrunnable = new Thread(new MyRunnable());
myrunnable.start();
答案 1 :(得分:2)
要启动线程,您需要从Thread
创建两个Runnable
并启动它们:
Thread t1 = new Thread(r);
Thread t2 = new Thread(a);
t1.start();
t2.start();
答案 2 :(得分:2)
将类r1和r2定义为:
public class Thread1 extends Thread {
@Override
public void run() {
System.out.println("r1");
try {
this.sleep(100);
} catch (Exception ex) {
}
}
}
public class Thread2 extends Thread {
@Override
public void run() {
System.out.println("r2");
try {
this.sleep(100);
} catch (Exception ex) {
}
}
}
public class ThreadTester {
public static void main(String[] args) {
Thread1 r = new Thread1();
Thread2 a = new Thread2();
r.start();
a.start();
}
}
使用Runnable:
public class HelloRunnable implements Runnable {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new Thread(new HelloRunnable())).start();
}
}
检查java documentation了解更多信息