思路:利用Object.wait()和Object.notify()方法进行线程间的通信。
代码:
public class MyThread implements Runnable {
private static int i = 1;
private byte[] s1;
public MyThread(byte[] s1) {
this.s1 = s1;
}
@Override
public void run() {
while (true) {
synchronized (s1) {
Thread t1 = Thread.currentThread();
System.out.println(t1.getName() + ":" + (i++));
/*if (i > 101) {//设置中断数字
s1.notify();
break;
}*/
s1.notify();
try {
s1.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
测试启动类:
public class Test {
public static void main(String[] args) {
byte[] s1 = new byte[1];
MyThread myThread = new MyThread(s1);
MyThread myThread2 = new MyThread(s1);
new Thread(myThread,"线程1").start();
new Thread(myThread2,"线程2").start();
}
}