import java.awt.Toolkit;
import javax.swing.*;
class appeal{
/*
 * 一个GUI窗体类,有一个构造函数,两个文本域显示内容的方法up,youth
 */
JFrame jf;
JTextArea jt;
int width = Toolkit.getDefaultToolkit().getScreenSize().width;//获得屏幕的宽
        int height = Toolkit.getDefaultToolkit().getScreenSize().height;//获得屏幕的高
public appeal(JFrame jf){
this.jf=jf;
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口时结束程序
jt=new JTextArea();
jf.add(jt);
jf.setSize(300, 300);
jf.setLocation((width-300) / 2, (height-300) / 2);//使窗体在屏幕中间显示
jf.setVisible(true);
}
synchronized void up(boolean available){
if(!available){
notifyAll();
return;
}
jt.append("向上吧;");
notifyAll();
try{
wait();
}catch(InterruptedException e)
{
System.out.println("Thread interrupted!");
}
}
synchronized void youth(boolean available){
if(!available){
notifyAll();
return;
}
jt.append("青年!\n");
notifyAll();
try{
wait();
}catch(InterruptedException e)
{
System.out.println("Thread interrupted!");
}
}
}
class MyThread implements Runnable{
/*
 * 一个线程类,继承了Runnable接口
 */
Thread thrd;
appeal apl;
MyThread(String name,appeal apl){
thrd=new Thread(this,name);
this.apl=apl;
thrd.start();
}
public void run(){
if(thrd.getName().equals("up")){
for(int i=0;i<10;i++)
apl.up(true);
apl.up(false);
}else{
for(int i=0;i<10;i++)
apl.youth(true);
apl.youth(false);
}
}
}public class TheradTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
 * 主函数,实现过线程
 */
JFrame jf=new JFrame("多线程");
appeal apl=new appeal(jf);
MyThread mt1=new MyThread("up",apl);
MyThread mt2=new MyThread("youth",apl);
try {
mt1.thrd.join();
mt2.thrd.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println("Main thread interrupted!");
}

}
}
青年!
向上吧;青年!
向上吧;青年!
向上吧;青年!
向上吧;青年!
向上吧;青年!
向上吧;青年!
向上吧;青年!
向上吧;青年!
向上吧;青年!
向上吧;
怎么才能实现每次开始运行都是mt1先运行?也就是每次都是:向上吧;青年!

解决方案 »

  1.   

    个人认为:只需notifyAll 与wait 方法结合使用就可以。
    粗略写一个类:应该可以满足你的要求。
    public class WaitObj {
    private boolean runBefore = false;

    public synchronized void before() throws Exception{
    System.out.print("good,");
    this.runBefore = true;
    this.notifyAll();
    this.wait();
    }

    public synchronized void after() throws Exception{
      if(!runBefore){
     this.wait();
      }
      System.out.println("job.");
      this.notifyAll();
      this.runBefore = false;
    }
    }
      

  2.   

    代码太长,没看。不过设置某个线程先执行,只要设置它的优先级为最优先,就可以了。td.setPriority(0);