Java代码
- public class Test implements Runnable {
- // 记录运行次数
- long times = 0;
- int id = 0;
- boolean flag = true;
- Test() {
- new Thread(this).start();
- }
- public void offAndCount() {
- if (flag)
- id++;
- flag = false;
- }
- public void on() {
- times++;
- System.out.print(""); //注释掉这句运行多次,取消注释再运行多次。分别记录 注释 与 未注释 运行的结果,可以发现print对线程同步有影响(猜测:print执行时间较长的原因)
- flag = true;
- }
- public String runtime() {
- return "On() execute times==" + times+" ID=="+id;
- }
- // 启动一个新线程
- public void createANewThread() {
- new Thread(new Runnable() {
- public void run() {
- while (true)
- try {
- Thread.sleep(1);
- //每隔1ms打开开关
- on();
- } catch (Exception e) {}
- }
- }).start();
- }
- @Override
- public void run() {
- createANewThread();
- //不断 关闭开关
- while (true)
- offAndCount();
- }
- public static void main(String[] args) {
- Test t = new Test();
- try {
- Thread.sleep(3000);
- } catch (Exception e) {}
- System.out.println(t.runtime());
- System.exit(0);
- }
- }