zoukankan      html  css  js  c++  java
  • 【Java】创建线程对象两种方式

    1.继承Thread类,重载run方法;
    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
        }
    });
    2.实现Runnable接口,实现run方法;
    public class RunnableDemo implements Runnable {
    
    	protected int countDown = 10;
    	private static int taskCount = 0;
    	private final int id = taskCount++;
    
    	public RunnableDemo() {
    	}
    
    	public RunnableDemo(int countDown) {
    		this.countDown = countDown;
    	}
    
    	public String status() {
    		return "#" + id + "(" + (countDown > 0 ? countDown : "LiftOff!") + ").";
    	}
    
    	@Override
    	public void run() {
    		while (countDown-- > 0) {
    			System.out.print(status());
    			Thread.yield();// 将CPU从一个线程转移给另一个线程
    		}
    	}
    
    	public static void main(String[] args) {
    
    		System.out.println("这个任务的run()不是单独的线程驱动,是在main()中直接调用");
    		RunnableDemo launch = new RunnableDemo();
    		launch.run();
    		System.out.println();
    		System.out.println("************************************");
    
    		System.out.println("在新线程中启动任务");
    		Thread thread = new Thread(new RunnableDemo());
    		thread.start();
    		System.out.println("Waiting for LiftOff");
    		System.out.println("************************************");
    
    		System.out.println("添加多个线程去驱动更多的任务");
    		for (int i = 0; i < 5; i++) {
    			new Thread(new RunnableDemo()).start();
    		}
    		System.out.println("Waiting for LiftOff");
    
    		System.out.println("************************************");
    		System.out.println("使用executor");
    		ExecutorService exec = Executors.newCachedThreadPool();
    		exec=Executors.newFixedThreadPool(5);
    		for (int i = 0; i < 5; i++) {
    			exec.execute(new RunnableDemo());
    		}
    		exec.shutdown();
    		
    		Thread t=new Thread(new Runnable() {
    			
    			@Override
    			public void run() {
    				// TODO Auto-generated method stub
    				
    			}
    		});
    	}
    
    }
    

      

  • 相关阅读:
    webpack学习总结
    jquery弹出下拉列表插件(实现kindeditor的@功能)
    html meta标签使用总结
    Techparty-广州Javascript技术专场(学习分享)
    一个三年工作经验的软件工程师的经验之谈
    cf--------(div1)1A. Theatre Square
    离线网页制作器(beta1.0)
    uva---(11549)CALCULATOR CONUNDRUM
    CF---(452)A. Eevee
    Uva----------(11078)Open Credit System
  • 原文地址:https://www.cnblogs.com/zeze/p/6564392.html
Copyright © 2011-2022 走看看