我想同时使用不同的run方法运行两个线程。可能吗?我在下面有简单的代码,但它们并不兼容。我只想每隔5秒运行第一个线程,第二个线程总是运行。
public static int x = 0;
public static void main(String[] args) throws InterruptedException{
Runnable r1 = new Runnable() {
public void run() {
x = x + 1;
System.out.println("increment x");
}
};
Runnable r2 = new Runnable() {
public void run() {
System.out.println("x is "+x);
}
};
while(true){
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
t1.sleep(5000);
}
}
答案 0 :(得分:3)
您的run()
方法仅增加x,打印并返回。一旦run方法返回,线程就会停止运行。如果你想要永远运行某些东西,你需要在run()
方法中使用循环。
此外,在没有任何同步的情况下访问共享变量不会产生可预测的结果。您的x
变量至少应该是不稳定的。最后,Thread.sleep()是一个静态方法。因此应该使用类名称来调用它:
Thread.sleep(5000L);
它使当前线程休眠。
下面是一个示例,其中一个线程每500毫秒递增x,另一个线程每隔100毫米打印x,并且两个线程在5秒后中断:
public class ThreadExample {
private static volatile int x;
private static class Incrementer implements Runnable {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
x++;
try {
Thread.sleep(500L);
}
catch (InterruptedException e) {
return;
}
}
}
}
private static class Reader implements Runnable {
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
System.out.println(x);
try {
Thread.sleep(100L);
}
catch (InterruptedException e) {
return;
}
}
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Incrementer());
Thread t2 = new Thread(new Reader());
t1.start();
t2.start();
try {
Thread.sleep(5000L);
}
finally {
t1.interrupt();
t2.interrupt();
}
}
}
答案 1 :(得分:0)
在while循环中,您每次都会创建新的Threads
然后start
,这就是您有这种行为的原因。
然后你需要在线程中移动while循环,这样它们就像下面一样:
public static volatile int x = 0;
public static void main(String[] args) throws InterruptedException{
Runnable r1 = new Runnable() {
public void run() {
while (true) {
x = x + 1;
System.out.println("increment x");
this.sleep(5000);
}
}
};
Runnable r2 = new Runnable() {
public void run() {
while(true){
System.out.println("x is "+x);
}
}
};
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
}
另请注意,应同步访问x
变量以查看正确的值。
BR。
答案 2 :(得分:0)
Thread t1;;
Thread t2;
while(true){
t1 = new Thread(r1);
t2= new Thread(r2);
t1.start();
t1.sleep(5000);
t2.start();
}
你正在添加代码是正确的,在t2.start()之前将代码放到t1.sleep(5000)。
答案 3 :(得分:-1)
public class Test {
public static int x = 0;
public static void main(String[] args) throws InterruptedException{
Runnable r1 = new Runnable() {
public void run() {
while(true){
x = x + 1;
System.out.println("increment x");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
Runnable r2 = new Runnable() {
public void run() {
while(true){
System.out.println("x is "+x);
}
}
};
Thread t1 = new Thread(r1);
Thread t2 = new Thread(r2);
t1.start();
t2.start();
// Thread.sleep(5000);
}
}
这样的事情......但要记住上面提到的要点