日期:2014-05-20 浏览次数:20663 次
public class ThreadTest3 { public static void main(String[] args) throws InterruptedException { String s = "xingxing"; MyThread mt = new MyThread(); Thread t = new Thread(mt); t.setName(s); t.start(); for(int i = 0;i < 20; i++){ System.out.println("我是主线程。i: " + i + " " + Thread.currentThread()); Thread.sleep(1000); if(i == 10 && Thread.currentThread() == t){ System.out.println("\n 醒工砖\n "); mt.call();} } } } class MyThread implements Runnable{ Thread th1; public void run() { for(int i = 0;i < 10;i++){ System.out.println("我是二线程。i: " + i + " " + Thread.currentThread()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } if(i == 5 && Thread.currentThread() == ){ // 这里我想加上一个判定条件,当前线程为二线程的时候,执行wait(); wat(); } } } public void call(){ notifyAll(); } public void wat(){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } }
public class ThreadTest3 { public static void main(String[] args) throws InterruptedException { String s = "xingxing"; MyThread mt = new MyThread(); Thread t = new Thread(mt); t.setName(s); t.start(); for(int i = 0;i < 20; i++){ System.out.println("我是主线程。i: " + i + " " + Thread.currentThread()); Thread.sleep(1000); if(i==10){//你原来的目的是想在主线程执行到第十次的时候把那个线程唤醒是吧? mt.send(10); } /*if(i == 10){ System.out.println("\n 醒工砖\n "); mt.call(); }*/ } } } class MyThread implements Runnable{ Thread th1; int m; public void run() { for(int i = 0;i < 10;i++){ System.out.println("我是二线程。i: " + i + " " + Thread.currentThread()); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } if(i == 5 ){ // “这里我想加上一个判定条件,当前线程为二线程的时候,执行wait();”这里你用到的Thread.currentThread()得到只能是当前线程也就是为你所说的二线程。所以这里不需要这个判断。 wai(); } } } public synchronized void call(){//要锁定 notifyAll(); } public synchronized void wai(){//同样要锁定 try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } public void send(int m){ this.m=m; if(m==10){ call(); } } }