主线程输出10个数,子线程输出100个数,主线程循环输出10个数..........循环50次。
package Threadtest;
public class testMain {
public static void main(String[] args) {
// 在内部类里访问局部变量printUtil,需要加 final
final PrintUtil printUtil = new PrintUtil();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 50; i++) {
printUtil.hundredPrint(i);
}
}
}).start();
for (int i = 0; i < 50; i++) {
printUtil.tenPrint(i);
}
}
}
class PrintUtil {
//线程间通信信号,默认主线程执行
private boolean signal=true;
public synchronized void tenPrint(int count){
if(!signal){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(count + "-------主线程第" + count + "次循环-------" + count);
for (int i = 0; i < 10; i++) {
System.out.println("ten print of:" + i);
}
signal=false;
this.notify();
}
public synchronized void hundredPrint(int count){
if(signal){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(count + "-------子线程第" + count + "次循环-------" + count);
for (int i = 0; i < 100; i++) {
System.out.println("hundred print of:" + i);
}
signal=true;
this.notify();
}
}