[关闭]
@v-cong 2016-03-22T15:33:40.000000Z 字数 1107 阅读 989

Java多线型


  1. import java.util.Date;
  2. public class StartThread {
  3. public void startY(){
  4. ThreadY ty = new ThreadY();
  5. ty.startThreadY();
  6. try{
  7. Thread.sleep(1000);
  8. } catch (InterruptedException e) {
  9. e.printStackTrace();
  10. }
  11. ty.stopThreadY();
  12. }
  13. public void startX() {
  14. Runnable runnX = new ThreadX();
  15. Thread threadX = new Thread(runnX);
  16. threadX.start();
  17. }
  18. public static void main(String[] args){
  19. StartThread test = new StartThread();
  20. test.startY();
  21. test.startX();
  22. }
  23. }
  24. class ThreadY extends Thread{
  25. private boolean isRunState = false;
  26. public void start(){
  27. this.isRunState = true;
  28. super.start();
  29. }
  30. public void run(){
  31. int i = 0;
  32. try {
  33. while (isRunState){
  34. this.setName("Thread-"+ i ++);
  35. System.out.println("线程Y:" + this.getName() + "正在运行");
  36. Thread.sleep(100);
  37. }
  38. }catch (Exception e ){
  39. }
  40. System.out.println(this.getName()+ "运行结束...");
  41. }
  42. public void setRunning(boolean isRunState){
  43. this.isRunState = isRunState;
  44. }
  45. public void startThreadY(){
  46. System.out.println("启动线程Y...");
  47. this.start();
  48. }
  49. public void stopThreadY(){
  50. System.out.println("结束线程Y。。。");
  51. this.setRunning(false);
  52. }
  53. }
  54. class ThreadX implements Runnable {
  55. private Date runnDate;
  56. public void run(){
  57. System.out.println("线程X已启动。。。");
  58. this.runDate = new Date();
  59. System.out.println("启动时间" + runDate.toLocaleString());
  60. }
  61. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注