Java 多线程 学习

1. 实现 Runnable 接口,包含run方法,这是要完成的任务
交给线程,通过new Tread(),start 启动
package thread;

public class LiftOff implements Runnable {
	protected int countDown = 10;
	private static int taskCount = 0;
	private final char id = (char)('A'+(taskCount++));
	
	public LiftOff() {}
	
	public LiftOff( int countDown )
	{
		this.countDown=countDown;
	}
	
	public String status ()
	{
		return  "#"+id+":"+countDown;
	}
	
	public void run()
	{
		while( countDown-->0 )
		{
			System.out.println(status());
			Thread.yield();
		}
	}
	
	public static void main(String [] args)
	{
		for(int i=0; i<10 ; i++)
		{
			new Thread( new LiftOff() ).start();
		}
	}
}


2. 使用线程池
线程池 CachedThreadPool,FiexedThreadPool 可控制定长,SingleThread 顺序执行
package thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class CachedThreadPool {
	public static void main( String [] args )
	{
		ExecutorService exec = Executors.newCachedThreadPool();
		for(int i=0;i<5;i++)
			exec.execute(new LiftOff(10));
	}
}


4. 休眠
TimeUnit.MILLISECONDS.sleep(100);

你可能感兴趣的:(java,thread,多线程)