Java_多线程实现

一个类两个接口

Tread类: 使用时继承Thread类
Runnable接口: 使用时实现Runnable接口
Callable接口: 使用时实现Callable接口

由于类只能单继承, 接口可以多继承, 所以尽量使用接口

Thread的继承(创建线程方式一)

/* 
 * 创建线程方式一:
 * 1, 创建: 继承Tread类 + 重写run
 * 2, 启动: 创建子类对象 + start
 *
 */

public class StartThread extends Thread{

	@Override
	public void run() {
		for(int i = 0; i < 20; i++) {
			System.out.println("music");
		}
	}
	
	public static void main(String[] args) {
		// 创建子类对象
		StartThread st = new StartThread();
	
		// 启动
		st.start();	// 不保证立即运行cpu调用
		
		for(int i = 0; i < 20; i++) {
			System.out.println("coding");
		}
	}
}

Runnable的实现(创建线程方式二)

  1. 创建目标对象
  2. 创建线程对象 + 关联目标对象
  3. 启动线程
/*
 * 创建线程方式二:
 * 1, 创建: 实现Runnable + 重写run
 * 2, 启动: 创建实现类对象 + Thread对象 + start
 * 
 * 推荐: 避免单继承的局限性, 优先使用接口
 * 方便共享资源
 */
public class StartRun implements Runnable{

	@Override
	public void run() {
		for(int i = 0; i < 20; i++) {
			System.out.println("music");
		}
	}
	
	public static void main(String[] args) {
/* 方法一: 声明引用 
		// 创建实现类对象
		StartRun sr = new StartRun();
		// 创建代理类对象
		Thread t = new Thread(sr);
		// 启动
		t.start();	// 不保证立即运行cpu调用
*/

//	方法二: 匿名(一个对象只使用一次)
		new Thread(new StartRun()).start();
		for(int i = 0; i < 20; i++) {
			System.out.println("coding");
		}
	}
}
/**********模拟龟兔赛跑示例程序************/
public class Racer implements Runnable {
	private static String winner;	// 共享资源
	@Override 
	public void run() {
		for(int steps = 1; steps <= 100; steps++) {
			// 模拟乌龟休息
			if(Thread.currentThread().getName().equals("rabbit") && steps%10 == 0) {
				try {
					Thread.sleep(10);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			System.out.println(Thread.currentThread().getName() + "---->" + steps);
			if(gameOver(steps)) {
				break;
			}
		}
	}
	
	private boolean gameOver(int steps) {
		if(null != winner ) {	// 分出胜负后, 通过共享变量结束另一个线程
			return true;
		} else {
			if(steps == 100) {
				winner = Thread.currentThread().getName();
				System.out.println("winner---->" + winner);
				return true;
			} 
		}
		return false;
	}
	
	public static void main(String[] args) {
		Racer racer = new Racer();
		new Thread(racer, "tortoise").start();
		new Thread(racer, "rabbit").start();
	}
	
}
package cn.zyb.thread;
/**
 * 共享资源, 并发
 * 
 * @author Administrator
 *
 */

public class Web12306 implements Runnable{
	// 票数
	private int ticketNumbers = 5;
	
	@Override
	public void run() {
		while(true) {
			if(ticketNumbers < 0) {
				break;
			}
			// 加入睡眠后线程不安全
//			try {
//				Thread.sleep(100);
//			} catch (InterruptedException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
			System.out.println(Thread.currentThread().getName() 
					+ "---->" + ticketNumbers--);
		}
	}
	
	public static void main(String[] args) {
		// 一份资源
		Web12306 web = new Web12306();
		
		// 多个代理
		new Thread(web, "zyb").start();
		new Thread(web, "zpy").start();
		new Thread(web, "haha").start();
	}
}
/*
zpy---->4
haha---->1
zyb---->2
zpy---->0
*/

Callable的实现(创建线程方式三)

  1. 创建目标对象
  2. 创建执行服务
  3. 提交执行
  4. 获取结果
  5. 关闭服务
/****************文件一******************/
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CDownloader implements Callable<Boolean> {
	private String url;
	private String name;
	
	public CDownloader(String url, String name) {
		this.url = url;
		this.name = name;
	}
	@Override
	public Boolean call() throws Exception{
		WebDownloader wd = new WebDownloader();
		wd.download(url, name);
		System.out.println(name);
		return true;
	}
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		CDownloader cd1 = new CDownloader("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1538910423159&di=9cad47c1aab60ebb7ab6ff71cfe20646&imgtype=0&src=http%3A%2F%2Fa.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2F377adab44aed2e73c3dc082b8a01a18b87d6fa84.jpg",
									"1.jpg");
		CDownloader cd2 = new CDownloader("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1538910447240&di=c821bb352f682af7ce07e335f05295c5&imgtype=0&src=http%3A%2F%2Fd.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2F203fb80e7bec54e77d03071cb4389b504ec26ac0.jpg",
									"2.jpg");
		CDownloader cd3 = new CDownloader("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1538910459543&di=f99f4f6848913e2edc015cc39bf15f79&imgtype=0&src=http%3A%2F%2Fd.hiphotos.baidu.com%2Fimage%2Fpic%2Fitem%2Fb64543a98226cffc254c32acb4014a90f603ea4e.jpg",
									"3.jpg");
		// 创建执行服务
		ExecutorService ser = Executors.newFixedThreadPool(3);
		// 提交执行
		Future<Boolean> result1 = ser.submit(cd1);
		Future<Boolean> result2 = ser.submit(cd2);
		Future<Boolean> result3 = ser.submit(cd3);
		// 获取结果
		boolean r1 = result1.get();
		boolean r2 = result1.get();
		boolean r3 = result1.get();
		// 关闭服务
		ser.shutdownNow();
	}
}

/****************文件二******************/

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

// 自定义包
import org.apache.commons.io.FileUtils;

/**
 * 下载
 * @author Administrator
 *
 */
public class WebDownloader {
	public void download(String url, String name) {
		try {
			FileUtils.copyURLToFile(new URL(url), new File (name));
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("不合法URL");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("下载失败");
		}
	}

}
posted @ 2018-10-08 12:22  张飘扬  阅读(88)  评论(0编辑  收藏  举报