public class ImplRunnable implements Runnable {
String thread_name;
int line = 10;//关键的共享变量
@Override
public void run() {
synchronized (this){//确保每个任务只执行一次
for(;0 < line;line--)
System.out.println(Thread.currentThread().getName() + ":::::::::::" +line);
}
}
public static void main(String[] args) {
/**
* 共同执行一个任务,前提是有共享变量line
*/
ImplRunnable ir = new ImplRunnable();
Thread th1 = new Thread(ir,"ImplRunnable001");
Thread th2 = new Thread(ir,"ImplRunnable002");
Thread th3 = new Thread(ir,"ImplRunnable003");
th1.start();
th2.start();
th3.start();
/**
* 每个thread都执行全部任务
*/
Thread th11 = new Thread(new ImplRunnable(),"ImplRunnable011");
Thread th12 = new Thread(new ImplRunnable(),"ImplRunnable012");
Thread th13 = new Thread(new ImplRunnable(),"ImplRunnable013");
th11.start();
th12.start();
th13.start();
}
}
多线程Runnable任务执行注意
最新推荐文章于 2023-06-06 09:21:54 发布