多线程简单控制示例。
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);
- // }
- }