Thread线程
2021-03-01 07:25
标签:public xtend read 总结 name 重写 tst 执行 方式 Thread线程 标签:public xtend read 总结 name 重写 tst 执行 方式 原文地址:https://www.cnblogs.com/xiahong/p/14453548.htmlpackage com.xiahong.base.Thread;
//创建线程方式一:1.继承Thread类 2.重写run()方法 3.调用start 开启线程
public class ThreadTest extends Thread{
@Override
public void run() {
//run方法线程体
for (int i = 0; i
package com.xiahong.base.Thread;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
//联系Thread ,实现多线程同步下载图片
public class ThreadTest1 extends Thread{
private String url;//网络图片地址
private String name; //保存的文件名
public ThreadTest1(String url,String name){
this.name=name;
this.url=url;
}
@Override
public void run() {
WebDownloader webDownloader=new WebDownloader();
webDownloader.downloader(url,name);
System.out.println("下载了文件名为"+name);
}
public static void main(String[] args) {
ThreadTest1 threadTest1 =new ThreadTest1("https://gd1.alicdn.com/imgextra/i4/4292439402/O1CN01REmz0J2JKATKbf1j5_!!4292439402.jpg_400x400.jpg","1.jpg");
ThreadTest1 threadTest2 =new ThreadTest1("https://gd1.alicdn.com/imgextra/i4/4292439402/O1CN01REmz0J2JKATKbf1j5_!!4292439402.jpg_400x400.jpg","2.jpg");
ThreadTest1 threadTest3 =new ThreadTest1("https://gd1.alicdn.com/imgextra/i4/4292439402/O1CN01REmz0J2JKATKbf1j5_!!4292439402.jpg_400x400.jpg","3.jpg");
//先下载t1
threadTest1.start();
//先下载t2
threadTest2.start();
//先下载t3
threadTest3.start();
}
}
//下载器
class WebDownloader{
//下载方法
public void downloader(String url,String name){
try {
FileUtils.copyURLToFile(new URL(url),new File(name));
} catch (IOException e) {
e.printStackTrace();
System.out.println("IO异常,downloader方法出现问题");
}
}
}
package com.xiahong.base.Thread;
//多个线程同时操作同一个对象
//买火车票的例子
//发现问题:多个线程操作同一个资源的情况下,线程不安全,数据紊乱
public class ThreadTest3 implements Runnable{
//票数
private int ticketNums=10;
@Override
public void run() {
while (true){
if(ticketNums拿到了第"+ticketNums--+"张票");
}
}
public static void main(String[] args) {
ThreadTest3 threadTest3 =new ThreadTest3();
new Thread(threadTest3,"小明").start();
new Thread(threadTest3,"老师").start();
new Thread(threadTest3,"黄牛党").start();
}
}
package com.xiahong.base.Thread;
//模拟龟兔赛跑
public class Race implements Runnable {
//胜利者
private static String winner;
@Override
public void run() {
for (int i = 0; i 跑了" + i + "步");
}
}
//判断是否完成比赛
private boolean gameOver(int steps) {
//判断是否有胜利者
if (winner != null) {
return true;
}
{
if (steps >= 100) {
winner = Thread.currentThread().getName();
System.out.println("winner is" + winner);
return true;
}
}
return false;
}
public static void main(String[] args) {
Race race = new Race();
new Thread(race, "兔子").start();
new Thread(race, "乌龟").start();
}
}
package com.xiahong.base.Thread;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
/*//线程创建方式3:实现Callable接口
* Callable的好处
* 1.可以定义返回值
* 2.可以抛出异常
* */
public class TestCallable implements Callable