两个线程轮流执行,分别打印出线程的名称,要求先打印Thread-0线程10次,在打印mian线程100次,打印Thread-0线程10次,在打印mian线程100次,如此反复50遍。package com.lsp.threadtest;public class ChangeOut implements Runnable {public void run() { for (int i = 0; i < 10; i++) { System.out.println("Thread-0线程"); }}}package com.lsp.threadtest;public class ChangTest {public static void main(String[] args) { ChangeOut co = new ChangeOut(); Thread t1 = new Thread(co); for (int i=0; i<50; i++) { t1.run(); for(int k=0; k<100; k++){ System.out.println("main线程"); } }
}
}
t1.start();
线程的执行是系统调度的,这样写不会得到你想要的结果
public class ThreadTest { static volatile boolean flag = true; // 用于同步控制 public static void main(String[] args) {
Object monitor = new Object(); // 用于同步控制的锁
ChangeOut changeOut = new ChangeOut(monitor);
Thread t1 = new Thread(changeOut);
t1.start(); for (int i = 0; i < 50; i++) {
synchronized (monitor) {
while (flag)
try {
monitor.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int j = 0; j < 100; j++) {
System.out.println("main线程");
}
flag = true;
monitor.notify();
}
} }
}class ChangeOut implements Runnable {
private Object monitor; public ChangeOut() {
} public ChangeOut(Object monitor) {
this.monitor = monitor;
} public void run() {
for (int i = 0; i < 50; i++) {
synchronized (monitor) {
while (!ThreadTest.flag)
try {
monitor.wait();
} catch (InterruptedException e) {
e.printStackTrace();
} for (int j = 0; j < 10; j++) {
System.out.println("Thread-0线程");
}
ThreadTest.flag = false;
monitor.notify();
}
}
}
}这是我使用同步控制给你写的代码,应该没有问题。如有疑问,欢迎到我空间提问。
看api哈
for (int i=0; i <50; i++) {
new Thread(t1).start();
// t1.run(); for(int k=0; k <100; k++){ System.out.println("main线程"); } }