我用getState,但是程序不能正常执行。请大侠指点。
用两个线程代指两个人(A,B),两人分别数数,从1到5,每数一次休眠0.5s,最后哪个先数到5,对方就埋单。下面是我的程序。public class MyThread extends Thread{
private String person;
public MyThread(String one){
person = one;
}
public void run(){
try{
for(int i = 0; i <= 9; i++){
System.out.println(person);
Thread.currentThread().sleep(500);
}
}catch(Exception e){
e.printStackTrace();
}
}
}public class MultiThread {
public static void main(String args[]){
MyThread myThread1 = new MyThread("A");
MyThread myThread2 = new MyThread("B");
myThread1.start();
State s1 = myThread1.getState();
myThread2.start();
State s2 = myThread2.getState();
if((!s1.equals("TERMINATED")) && (s2.equals("TERMINATED"))){
System.out.print("A埋单");
}else if((!s2.equals("TERMINATED")) && (s1.equals("TERMINATED"))){
System.out.print("B埋单");
}
}
}

解决方案 »

  1.   

    执行是start的意思吗?如果状态不是NEW,就说明已经执行了/**
         * A thread state.  A thread can be in one of the following states: 
         * <ul>
         * <li>{@link #NEW}<br>
         *     A thread that has not yet started is in this state.
         *     </li>
         * <li>{@link #RUNNABLE}<br>
         *     A thread executing in the Java virtual machine is in this state. 
         *     </li>
         * <li>{@link #BLOCKED}<br>
         *     A thread that is blocked waiting for a monitor lock 
         *     is in this state. 
         *     </li>
         * <li>{@link #WAITING}<br>
         *     A thread that is waiting indefinitely for another thread to 
         *     perform a particular action is in this state. 
         *     </li>
         * <li>{@link #TIMED_WAITING}<br>
         *     A thread that is waiting for another thread to perform an action 
         *     for up to a specified waiting time is in this state. 
         *     </li>
         * <li>{@link #TERMINATED}<br> 
         *     A thread that has exited is in this state.
         *     </li>
         * </ul>
         *
         * <p>
         * A thread can be in only one state at a given point in time. 
         * These states are virtual machine states which do not reflect
         * any operating system thread states.
         * 
         * @since   1.5
         * @see #getState
         */
        public enum State {
            /**
             * Thread state for a thread which has not yet started.
             */
            NEW,
            
            /**
             * Thread state for a runnable thread.  A thread in the runnable
             * state is executing in the Java virtual machine but it may
             * be waiting for other resources from the operating system
             * such as processor.
             */
            RUNNABLE,
            
            /**
             * Thread state for a thread blocked waiting for a monitor lock.
             * A thread in the blocked state is waiting for a monitor lock
             * to enter a synchronized block/method or 
             * reenter a synchronized block/method after calling
             * {@link Object#wait() Object.wait}.
             */
            BLOCKED,
        
            /**
             * Thread state for a waiting thread.
             * A thread is in the waiting state due to calling one of the 
             * following methods:
             * <ul>
             *   <li>{@link Object#wait() Object.wait} with no timeout</li>
             *   <li>{@link #join() Thread.join} with no timeout</li>
             *   <li>{@link LockSupport#park() LockSupport.park}</li>
             * </ul>
             * 
             * <p>A thread in the waiting state is waiting for another thread to
             * perform a particular action.  
             *
             * For example, a thread that has called <tt>Object.wait()</tt>
             * on an object is waiting for another thread to call 
             * <tt>Object.notify()</tt> or <tt>Object.notifyAll()</tt> on 
             * that object. A thread that has called <tt>Thread.join()</tt> 
             * is waiting for a specified thread to terminate.
             */
            WAITING,
            
            /**
             * Thread state for a waiting thread with a specified waiting time.
             * A thread is in the timed waiting state due to calling one of 
             * the following methods with a specified positive waiting time:
             * <ul>
             *   <li>{@link #sleep Thread.sleep}</li>
             *   <li>{@link Object#wait(long) Object.wait} with timeout</li>
             *   <li>{@link #join(long) Thread.join} with timeout</li>
             *   <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li> 
             *   <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li>
             * </ul>
             */
            TIMED_WAITING,        /**
             * Thread state for a terminated thread.
             * The thread has completed execution.
             */
            TERMINATED;
        }
      

  2.   

    在线程的run()中用println打印数据不就行了,没执行一次就打新一次数据
      

  3.   

    嗯,挺有意思的
    我做了一个
    但是没有做到当一个喊出我赢了立即终止另外一个人的工作/*
     * file: BillPlay.java
     * class: BillPlay
     *
     * description: 
     *
     * @author:  leisore
     * @version: V1.0.0
     */
    package cn.leisore.daily._2010_07_01;public class BillPlay {    public static void main(String[] args) {
            ShareMonitor sm = new ShareMonitor();        Person p1 = new Person("leisore", sm);
            Person p2 = new Person("jackson", sm);        p1.start();
            p2.start();
        }    private static class Person extends Thread {
            int counter = 0;
            String name = null;
            ShareMonitor sm = null;        Person(String name, ShareMonitor sm) {
                this.name = name;
                this.sm = sm;
            }        public void run() {
                while (!Thread.interrupted()) {
                    synchronized (sm) {
                        if (sm.gameEnd) {
                            System.out.println(name + " said:"
                                    + "I'm losed, and I will pay.");
                            break;
                        } else if (++counter == 5) {
                            sm.gameEnd = true;
                            System.out.println(name + " said:" + "My counter is " + counter);
                            System.out.println(name + " said:"
                                    + "I'm got it, and you will pay.");
                            break;
                        }
                    }                try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(name + " said:" + "My counter is " + counter);
                }
            }
        }    private static class ShareMonitor {
            boolean gameEnd = false;
        }
    }
    输出:
    leisore said:My counter is 1
    jackson said:My counter is 1
    jackson said:My counter is 2
    leisore said:My counter is 2
    jackson said:My counter is 3
    leisore said:My counter is 3
    jackson said:My counter is 4
    jackson said:My counter is 5
    jackson said:I'm got it, and you will pay.
    leisore said:My counter is 4
    leisore said:I'm losed, and I will pay.
      

  4.   

    写个玩玩package ck;public class An {
    public int n;
    public static boolean bz = true;
    }package ck;import java.util.Random;public class Main extends Thread {
    private final An an;
    private final Random random; 
    public Main(String name, An an){
    super(name);
    this.an = an;
    random = new Random();
    }

    public static void main(String[] args) {
     
    new Main("随想", new An()).start();
    new Main("楼主", new An()).start();
    }

    @Override
    public void run() {
    while(An.bz){
    if(an.n == 5){
    System.out.println(getName()+"说: 我先数完事 你别数了 你买单吧!!!");
    An.bz = false;
    }

    System.out.println(" 小孩 "+getName()+" 数数 "+an.n++);
    try {
    sleep(random.nextInt(500)); // 0.5毫秒之内的随机数 数数耗时
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    }
    /**
     * print  --  >>
     小孩 随想 数数 0
     小孩 楼主 数数 0
     小孩 随想 数数 1
     小孩 随想 数数 2
     小孩 楼主 数数 1
     小孩 随想 数数 3
     小孩 楼主 数数 2
     小孩 随想 数数 4
    随想说: 我先数完事 你别数了 你买单吧!!!
     小孩 随想 数数 5  */
    }
      

  5.   

    才写的这段代码会有出现几率很小的bug 停止的不是那么及时
      

  6.   

    /**
     * 启动多个计数器,并得到最先完成的那个。
     *
     * @author yiding.he
     */
    public class MultipleCounter {    /**
         * 锁对象,用于挂起主线程和保存最先数完的计数器
         */
        private static final Counter[] lock = new Counter[1];    /**
         * 程序入口
         *
         * @param args 参数
         *
         * @throws Exception 如果出现错误
         */
        public static void main(String[] args) throws Exception {
            int numberOfCounters = 5;   // 计数器数目
            int countUpTo = 5;          // 每个计数器计数次数        // 启动计数器
            for (int i = 0; i < numberOfCounters; i++) {
                String name = "counter " + (i + 1);
                new Counter(name, countUpTo).start();
            }        // 等待第一个数完的计数器
            synchronized (lock) {
                lock.wait();            System.out.println(lock[0].getThreadName() + " finished first.");
            }
        }    /**
         * 计数器线程
         */
        private static class Counter extends Thread {        private int countUpTo;        private String name;        private Counter(String name, int countUpTo) {
                setDaemon(true);            this.name = name;
                this.countUpTo = countUpTo;
            }        public String getThreadName() {
                return name;
            }        @Override
            public void run() {
                Random r = new Random();            // 计数
                int counter = 0;
                while (counter < countUpTo) {
                    sleep(r);
                    counter++;                System.out.println(this.getThreadName() + ": " + counter);
                }            // 提醒主线程
                synchronized (lock) {
                    lock[0] = this;
                    lock.notify();
                }
            }        private void sleep(Random r) {
                try {
                    Thread.sleep(r.nextInt(2500) + 500);
                } catch (InterruptedException e) {
                    // nothing to do
                }
            }
        }
    }
      

  7.   

    我也来试试 
    import java.util.concurrent.CountDownLatch;public class MyThread extends Thread {
    private static volatile Boolean flag = false;
    private static CountDownLatch cd = new CountDownLatch(2); // 主程序等待线程用,用于计算主程序耗时 public static void main(String[] args) throws InterruptedException {
    long timeStart = System.currentTimeMillis();
    Readcount myThread1 = new Readcount("A");
    Readcount myThread2 = new Readcount("B");
    myThread1.start();
    myThread2.start();
    cd.await();
    System.out.println("Main thread cost time "
    + (System.currentTimeMillis() - timeStart));
    } static class Readcount extends Thread {
    private String person;
    private int i = 0;
    private int count = 10; public Readcount(String one) {
    person = one;
    } public void run() {
    String word = "I'm loster";
    try {
    while (gameNotOver()) {
    synchronized (flag) {
    if (gameNotOver()) {
    System.out.println(person + " say count " + ++i);
    if (i == count) {
    flag = true; // 游戏结束
    word = "I'm winner ";
    }
    }
    }
    Thread.sleep((long) (Math.random() * 100)); // 停顿 100以内的随机数
    }
    System.out.println(person + " say " + word);
    cd.countDown();
    } catch (Exception e) {
    e.printStackTrace();
    }
    } private boolean gameNotOver() {
    return !flag;
    }
    }
    }
      

  8.   

    程序中的错误,在于,另外2个线程可能还都没开始执行,你就判断了它们的状态。
    至少你得写个while等至少一个线程运行结束吧
      

  9.   

    start()只是通知虚拟机,你有个线程要启动,至于何时启动,无法预知的。而你start()之后立即调用getState().返回的状态很可能是还未执行