创建线程的方式:
1: 继承 Thread
- package com.sxt.thread;
- /**
- * 创建线程方式一:
- * 1, 创建: 继承 Thread + 重写 run
- * 2, 启动: 创建子类对象 + start
- * @author
- *
- */
- public class StartThread extends Thread{
- /**
- * 线程入口点
- */
- @Override
- public void run() {
- for(int i=0;i<20;i++) {
- System.out.println("一边听歌");
- }
- }
- public static void main(String[] args) {
- // 创建子类对象
- StartThread st =new StartThread();
- // 启动
- st.start(); // 不保证立即运行 CPU 调用
- //st.run(); // 普通方法调用
- for(int i=0;i<20;i++) {
- System.out.println("一边 coding");
- }
- }
- }
- View Code
2: 实现 Runnable 接口
- package com.sxt.thread;
- /**
- * 创建线程方式二:
- * 1, 创建: 实现 Runnable + 重写 run
- * 2, 启动: 创建实现类对象 +Thread 对象 + start
- *
- * 推荐: 避免单继承的局限性, 优先使用接口
- * 方便共享资源
- * @author
- *
- */
- public class StartRun implements Runnable{
- /**
- * 线程入口点
- */
- @Override
- public void run() {
- for(int i=0;i<20;i++) {
- System.out.println("一边听歌");
- }
- }
- public static void main(String[] args) {
- /*// 创建实现类对象
- StartRun sr =new StartRun();
- // 创建代理类对象
- Thread t =new Thread(sr);
- // 启动
- t.start(); // 不保证立即运行 CPU 调用
- */
- new Thread(new StartRun()).start();
- //st.run(); // 普通方法调用
- for(int i=0;i<20;i++) {
- System.out.println("一边 coding");
- }
- }
- }
- View Code
3: 实现 Callable 接口 (线程安全)
- package com.sxt.thread;
- 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;
- /**
- * 了解创建线程的方式三:
- *
- * @author
- *
- */
- 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("http://upload.news.cecb2b.com/2014/0511/1399775432250.jpg","phone.jpg");
- CDownloader cd2 =new CDownloader("http://p1.pstatp.com/large/403c00037462ae2eee13","spl.jpg");
- CDownloader cd3 =new CDownloader("http://5b0988e595225.cdn.sohucs.com/images/20170830/d8b57e0dce0d4fa29bd5ef014be663d5.jpeg","success.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();
- System.out.println(r3);
- // 关闭服务:
- ser.shutdownNow();
- }
- }
- View Code
线程控制方法:
sleep
暂停: 当前线程被阻塞, 任务回到待添加状态;
yield
礼让: 让当前正在执行的线程暂停, 不是阻塞线程, 而是将线程从运行状态转为就绪状态, 让 CPU 调度器重新调用.
来源: http://www.bubuko.com/infodetail-3157357.html