Java代码

  1. package cn.itcast;
  2.  
  3. /**
  4. * 传统线程
  5. */
  6. public class TraditionalThread {
  7. public static void main(String[] args) {
  8. // 第一种方法
  9. Thread thread = new Thread() {
  10. @Override
  11. public void run() {
  12. while (true) {
  13. try {
  14. Thread.sleep(1000);
  15. } catch (InterruptedException e) {
  16. e.printStackTrace();
  17. }
  18. System.out.println("thread name:" + Thread.currentThread().getName());
  19. System.out.println("2:" + this.getName());
  20. }
  21. }
  22. };
  23. thread.start();
  24.  
  25. // 第二种方法
  26. Thread thread2 = new Thread(new Runnable() {
  27. @Override
  28. public void run() {
  29. while (true) {
  30. try {
  31. Thread.sleep(1000);
  32. } catch (InterruptedException e) {
  33. e.printStackTrace();
  34. }
  35. System.out.println("runnable name:" + Thread.currentThread().getName());
  36. }
  37. }
  38. });
  39. thread2.start();
  40.  
  41. // 第三种方法 执行的是thread部分,覆盖了父类的run()方法
  42. new Thread(new Runnable() {
  43. public void run() {
  44. while (true) {
  45. try {
  46. Thread.sleep(500);
  47. } catch (InterruptedException e) {
  48. e.printStackTrace();
  49. }
  50. System.out.println("runnable :"
  51. + Thread.currentThread().getName());
  52.  
  53. }
  54. }
  55. }) {
  56. public void run() {
  57. while (true) {
  58. try {
  59. Thread.sleep(1000);
  60. } catch (InterruptedException e) {
  61. e.printStackTrace();
  62. }
  63. System.out.println("thread :"
  64. + Thread.currentThread().getName());
  65.  
  66. }
  67. }
  68. }.start();
  69. }
  70. }