Java多线程学习笔记1——线程的实现方式以及定时器的使用

一、当一个匿名线程中初始化了runable对象,thread又重写了run方法,会触发哪个run方法呢?

	public static void main(String[] args) {
		new Thread( new Runnable() {  //构造函数中传入了runable
			@Override
			public void run() {
				while (true) {
					try {Thread.sleep(1000);} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println(Thread.currentThread().getName() + "-----------");
				}
			}
		}) {   //重写了run方法
			public void run() {   
				while (true) {
					try {Thread.sleep(1000);} catch (InterruptedException e) {
						e.printStackTrace();
					}
					System.out.println(Thread.currentThread().getName() + "======");
				}
			};
		}.start();
	}
    上面代码是是怎么执行两个run方法呢?先查看下thread的源代码查看线程的运行过程

   

 public Thread(Runnable target) {   init(null, target, "Thread-" + nextThreadNum(), 0); } 

 private void init(ThreadGroup g, Runnable target, String name, long stackSize, AccessControlContext acc) {
        if (name == null) {    throw new NullPointerException("name cannot be null"); }
        this.name = name;
        Thread parent = currentThread();
        SecurityManager security = System.getSecurityManager();
        if (g == null) {
            if (security != null) {
                g = security.getThreadGroup();
            }
            if (g == null) {
                g = parent.getThreadGroup();
            }
        }
        g.checkAccess();
        if (security != null) {
            if (isCCLOverridden(getClass())) {
                security.checkPermission(SUBCLASS_IMPLEMENTATION_PERMISSION);
            }
        }
        g.addUnstarted();
        this.group = g;
        this.daemon = parent.isDaemon();
        this.priority = parent.getPriority();
        if (security == null || isCCLOverridden(parent.getClass()))
            this.contextClassLoader = parent.getContextClassLoader();
        else
            this.contextClassLoader = parent.contextClassLoader;
        this.inheritedAccessControlContext =
                acc != null ? acc : AccessController.getContext();
        this.target = target;
        setPriority(priority);
        if (parent.inheritableThreadLocals != null)
        this.inheritableThreadLocals = ThreadLocal.createInheritedMap(parent.inheritableThreadLocals);
        this.stackSize = stackSize;
        tid = nextThreadID();
    }
@Override
    public void run() {
        if (target != null) {
            target.run();
        }
    }

        可以看出如果构造函数中传入了target使用传入对象的run方法或则执行thread重写的run方法。由于重写了对象,所以原来的run方法不执行。所以执行结果为:Thread-0======

 二:定时器 2秒和4秒交替执行

public class TraditionTimer {
	static int count = 0;
	public static void main(String[] args) {
		class MyTimerTask extends TimerTask {		
                        @Override
			public void run() {
				count++;
				System.out.println("i am work " + 2000 * (count % 2 + 1) + " s");
				new Timer().schedule(new MyTimerTask(), 2000 * (count % 2 + 1));
			}
		}
		// 初始化时候执行
		new Timer().schedule(new MyTimerTask(), 2000);
	}
}
    以上代码可以实现此功能。

猜你喜欢

转载自blog.csdn.net/zhangkang65/article/details/79189697