java中两个线程如何判定一个线程是否已经执行

ly_littlefish 2010-07-01 10:26:52
我用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埋单");
}
}
}
...全文
732 18 打赏 收藏 转发到动态 举报
写回复
用AI写文章
18 条回复
切换为时间正序
请发表友善的回复…
发表回复
小湘eeeee 2010-07-01
  • 打赏
  • 举报
回复
写个玩玩

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

*/
}

ducksma 2010-07-01
  • 打赏
  • 举报
回复
5楼的程序牛B。。。。
leisore 2010-07-01
  • 打赏
  • 举报
回复
嗯,挺有意思的
我做了一个
但是没有做到当一个喊出我赢了立即终止另外一个人的工作

/*
* 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.
wenlonghor616 2010-07-01
  • 打赏
  • 举报
回复
在线程的run()中用println打印数据不就行了,没执行一次就打新一次数据
ly_littlefish 2010-07-01
  • 打赏
  • 举报
回复
题目描述有点问题,是数到10,不是5.意思就是两个线程不断打印A、B,判断哪个线程先打印完并且打印出相应结果
getmydream 2010-07-01
  • 打赏
  • 举报
回复
对于线程,刚开始,感觉不好理解~~~~~~
dracularking 2010-07-01
  • 打赏
  • 举报
回复
执行是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;
}
「已注销」 2010-07-01
  • 打赏
  • 举报
回复
start()只是通知虚拟机,你有个线程要启动,至于何时启动,无法预知的。而你start()之后立即调用getState().返回的状态很可能是还未执行
「已注销」 2010-07-01
  • 打赏
  • 举报
回复
程序中的错误,在于,另外2个线程可能还都没开始执行,你就判断了它们的状态。
至少你得写个while等至少一个线程运行结束吧
ly_littlefish 2010-07-01
  • 打赏
  • 举报
回复
[Quote=引用 11 楼 yidinghe 的回复:]
Java code
/**
* 启动多个计数器,并得到最先完成的那个。
*
* @author yiding.he
*/
public class MultipleCounter {

/**
* 锁对象,用于挂起主线程和保存最先数完的计数器
*/
private static final Counter[] lock = new ……
[/Quote]

我是菜鸟,所以你的代码我得多研究研究……
感谢以上各位大神的指点,不过还是希望各位大声能指点程序中的逻辑错误
毕竟这样对我的学习更有好处
xinlan1022 2010-07-01
  • 打赏
  • 举报
回复
[Quote=引用 11 楼 yidinghe 的回复:]

Java code
/**
* 启动多个计数器,并得到最先完成的那个。
*
* @author yiding.he
*/
public class MultipleCounter {

/**
* 锁对象,用于挂起主线程和保存最先数完的计数器
*/
private static final Counter[] lock = new Counter[1……
[/Quote]

唤醒主线程之后,其他线程为什么停止了,求解。。。
zqfddqr 2010-07-01
  • 打赏
  • 举报
回复
判断线程的名字吧
Kanepan 2010-07-01
  • 打赏
  • 举报
回复
我也来试试


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;
}
}
}
小湘eeeee 2010-07-01
  • 打赏
  • 举报
回复
[Quote=引用 10 楼 jspwoai 的回复:]

引用 8 楼 mysd76 的回复:
才写的这段代码会有出现几率很小的bug 停止的不是那么及时



你的逻辑代码错在if 线程还在执行中 你就已经判断完了!
[/Quote]
你说的不对
捏造的信仰 2010-07-01
  • 打赏
  • 举报
回复
/**
* 启动多个计数器,并得到最先完成的那个。
*
* @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
}
}
}
}
JSPwoai 2010-07-01
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 mysd76 的回复:]
才写的这段代码会有出现几率很小的bug 停止的不是那么及时
[/Quote]


你的逻辑代码错在if 线程还在执行中 你就已经判断完了!
ly_littlefish 2010-07-01
  • 打赏
  • 举报
回复
多谢多谢楼上几位大神~~
不过我还是没有搞清楚我的逻辑错误
可以帮我看看我的逻辑错误不,多谢
明天来结贴哈
小湘eeeee 2010-07-01
  • 打赏
  • 举报
回复
才写的这段代码会有出现几率很小的bug 停止的不是那么及时

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧