Java多线程在继承runnable时,run方法中能写循环吗? 如果想多个线程能共用一个循环能做到吗?
可以,但是要有一个退出循环的条件
多个线程共用一个循环好像意义不大,线程是独立于其它的线程去执行一些特定的任务。一般这个任务是固定的,或者是同类型的。多个线程之间共享的只是这个线程结束的条件。双如
static volatile boolean flag = true;
public void run(){
while(flag){
//执行操作
}
}
这时外部线程可以改变flag,使用线程停止。
run中当然可以写循环。多个线程共用一个循环,可以这么实现,主线程执行循环,工作线程同步。
1、run()方法和其他方法是一样的,当然可以写循环
2、使用sychronized块
主类
public class MyThread {
public static void main(String[] args) throws Exception{
Thread1 t = new Thread1();
Thread mt1 = new Thread(t);
Thread mt2 = new Thread(t);
mt1.start();
mt2.start();
}
}
线程类
public class Thread1 implements Runnable{
public synchronized void run(){
char c = 'A';
try {
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
for(int i = 0; i < 14; i ++){
System.out.println(Thread.currentThread().getName() + "--->" + c);
c++;
}
}
}
public class ThreadEx implements Runnable {
char c = 'A';
public void run() {
while (true) {
System.out.println(Thread.currentThread().getName() + "--->" + c);
if ((int) c > ('A'+24)) {
break;
}
c++;
}
}
public static void main(String[] args) throws Exception {
ThreadEx t = new ThreadEx();
Thread mt1 = new Thread(t);
Thread mt2 = new Thread(t);
mt1.start();
mt2.start();
}
}
首先纠正版主个错误,runnable是个接口,应该说实现不能说继承。
1、run方法当中当然可以写循环
2、多个线程可以公用一个循环。这要考虑同步问题,可以加一个同步锁,避免在该线程没有完成操作之前。
synchronized (this) {
for(int i=0;i<10;i++){
System.out.println(Thread.currentThread()+"i="+i);
}
}
当然可以,共用循环,需要共享循环条件