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"); } } }
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"); } } }
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(); } }
sleep
暂停: 当前线程被阻塞,任务回到待添加状态;
yield
礼让: 让当前正在执行的线程暂停,不是阻塞线程,而是将线程从运行状态转为就绪状态,让CPU调度器重新调用.
如果调用了yield方法之后,没有其他等待执行的线程,这个时候当前线程就会马上恢复执行!
join
插队: 阻塞指定线程等到另一个线程完成以后再继续执行
原文:https://www.cnblogs.com/jiefangzhe/p/11362071.html