主线程启动两个线程,并输出BEBEBE……BE...BE的字符串。要求,两个子线程分别连续输出B和E。

来源:互联网 发布:apache 虚拟主机 编辑:程序博客网 时间:2024/06/06 23:31
package thread;public class MyThreadTest {private static final int _REPET_TIME = 1000; //限定次数,方便面测试结果private volatile int times = 0;//有synchronized,不需要volatileprivate synchronized void print(String s) {try {if (s.equals("B")) {this.notify();System.out.print("B");this.wait();} else if (s.equals("E")) {this.notify();System.out.print("E");this.wait();}times ++ ;//if(times > 300) {//System.out.print(Thread.currentThread().getName());//}} catch (Exception e) {}}public static void main(String[] args) {final MyThreadTest t = new MyThreadTest();Thread tb = new Thread(new Runnable() {public void run() {while(t.times < _REPET_TIME ) {t.print("B");}}});Thread te = new Thread( new Runnable() {public void run() {while(t.times < _REPET_TIME) {t.print("E");}}});tb.start();te.start();}}

原创粉丝点击