Java代码

  1. public class Test implements Runnable {
  2. // 记录运行次数
  3. long times = 0;
  4. int id = 0;
  5. boolean flag = true;
  6.  
  7. Test() {
  8. new Thread(this).start();
  9. }
  10.  
  11. public void offAndCount() {
  12. if (flag)
  13. id++;
  14. flag = false;
  15. }
  16.  
  17. public void on() {
  18. times++;
  19. System.out.print(""); //注释掉这句运行多次,取消注释再运行多次。分别记录 注释 与 未注释 运行的结果,可以发现print对线程同步有影响(猜测:print执行时间较长的原因)
  20. flag = true;
  21. }
  22.  
  23. public String runtime() {
  24. return "On() execute times==" + times+" ID=="+id;
  25. }
  26.  
  27. // 启动一个新线程
  28. public void createANewThread() {
  29. new Thread(new Runnable() {
  30. public void run() {
  31. while (true)
  32. try {
  33. Thread.sleep(1);
  34. //每隔1ms打开开关
  35. on();
  36. } catch (Exception e) {}
  37. }
  38. }).start();
  39. }
  40.  
  41. @Override
  42. public void run() {
  43. createANewThread();
  44. //不断 关闭开关
  45. while (true)
  46. offAndCount();
  47. }
  48.  
  49. public static void main(String[] args) {
  50. Test t = new Test();
  51. try {
  52. Thread.sleep(3000);
  53. } catch (Exception e) {}
  54. System.out.println(t.runtime());
  55. System.exit(0);
  56. }
  57.  
  58. }