您的位置:首页 > 编程语言 > Java开发

Java多线程简单示例

2012-04-11 00:29 302 查看
多线程简单控制示例。
1. extends Thread.

package cn.com.keke.thread.test;
/**
* extends Thread
* @author player
*
*/
public class MyThread extends Thread {

//线程执行条件
private boolean t;

public MyThread(boolean b) {
this.t = b;
}

public void run() {
if (this.t) {
System.out.print(" T ");
} else {
System.out.print(" F ");
}
}

public static void main(String[] args) {
Thread t1 = new MyThread(true);
Thread t2 = new MyThread(false);
t1.start();
t2.start();

// Thread 成员变量threadStatus 作怪
//      int i = 0;
//      do {
//          t1.start(); //throw runtime exception
//          t2.start(); //throw runtime exception

//          new Thread(t1).start(); //line is ok
//          new Thread(t2).start(); // line is ok
//          i++;
//      } while (i < 5);
}
}

2 implements Runnable.

package cn.com.keke.thread.test;
/**
* implements Runnable
* @author player
*
*/
public class MyThread2 implements Runnable {

private boolean t;

public MyThread2(boolean b) {
this.t = b;
}

public void run() {
if (t) {
System.out.print(" T ");
} else {
System.out.print(" F ");
}
}

public static void main(String[] args) {
MyThread2 t1 = new MyThread2(true);
MyThread2 t2 = new MyThread2(false);

Thread tt1 = new Thread(t1);
Thread tt2 = new Thread(t2);

tt1.start();
tt2.start();

//      // Thread threadStatus 作怪
//      int i = 0;
//      do {
//          tt1.start();//throw runtime exception
//          tt2.start();//throw runtime exception
//
//          new Thread(t1).start();//line is ok
//          new Thread(t2).start();//line is ok
//          i++;
//      } while (i < 5);
//  }

}


本文出自 “走進地铁等風景” 博客,请务必保留此出处http://cnctocn.blog.51cto.com/4183095/831130
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: