java多线性--线程创建
什么是多线程:不同的功能同时进行
Process(进程)与Thread(线程)
- 进程是执行程序的一次执行过程,是一个动态的概念。是系统分配资源的单位。
- 一个进程分为多个线程,一个进程中至少包含一个线程。线程是CPU调度和执行的单位。
线程创建
创建线程的三种方式:
- Thread:继承 Thread类
- Runnable:实现Runnable接口
- Callable:实现Callable接口 (了解)
Thread
-
自定义线程类继承Thread类。
-
重写其中的run()方法,编写线程执行体。
-
创建线程对象,调用start()方法启动线程。
package com.ssl.demo01;
//创建线程方式1:继承Thread类,重写run方法,调用start()方法
//总结:线程开启不一定立即执行,由CPU调度执行。
public class TestThread1 extends Thread{
//重写run方法
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("我在看代码--"+i);
}
}
public static void main(String[] args) {
//创建线程对象,调用start方法
TestThread1 testThread1 = new TestThread1();
testThread1.start(); //交替执行
//testThread1.run(); 先执行完,再走主线程。
//main线程 主线程
for (int i = 0; i < 20; i++) {
System.out.println("我在学习多线程---"+i);
}
}
}
练习下载图片
apache下载:
http://commons.apache.org/proper/commons-io/
package com.ssl.demo01;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.lang.String;
//练习Thread,实现多线程同步下载图片
public class TestThread2 extends Thread{
private String url;
private String name;
//构造器
public TestThread2(String url, String name){
this.url = url;
this.name = name;
}
@Override
public void run() {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url,name);
System.out.println("下载了文件名为:"+name);
}
public static void main(String[] args) {
TestThread2 test1 = new TestThread2("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwx3.sinaimg.cn%2Fmw690%2F006a7Fqsly1h6l1m1o2v8j31o02yo7wi.jpg&refer=http%3A%2F%2Fwx3.sinaimg.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1667102238&t=2663277ec5f007ad772e6cface75ec86","1.png");
TestThread2 test2 = new TestThread2("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fbkimg.cdn.bcebos.com%2Fpic%2F37d12f2eb9389b504fc209f70a7af2dde71190efc04c&refer=http%3A%2F%2Fbkimg.cdn.bcebos.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1667102500&t=ce4bf55425348082daa6f6e5132a8920","2.png");
TestThread2 test3 = new TestThread2("https://img1.baidu.com/it/u=4282593950,4216695015&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=515","3.png");
TestThread2 test4 = new TestThread2("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_bt%2F0%2F11324654676%2F1000.jpg&refer=http%3A%2F%2Finews.gtimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1667102566&t=e9f6e5a7c126a283489789301cacb584","4.png");
test1.start();
test2.start();
test3.start();
test4.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方法出问题");
}
}
}
Runnable
步骤:
- 定义MyRunable类实现Runable接口
- 实现run()方法
- 创建线程对象,调用start()方法启动线程
package com.ssl.demo01;
//创建线程方法2:实现runnable接口,重写run方法,执行线程需要丢入runnable接口实现类,调用start方法。
public class TestThread3 implements Runnable{
@Override
public void run() {
//run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("我在看代码--"+i);
}
}
public static void main(String[] args) {
//创建线程对象
TestThread3 testThread3 = new TestThread3();
//创建一个Thread; 把实现对象丢进去。
Thread thread = new Thread(testThread3);
thread.start();
//main线程 主线程
for (int i = 0; i < 20; i++) {
System.out.println("我在学习多线程--"+i);
}
}
}
练习:
package com.ssl.demo01;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class TestThread4 implements Runnable{
private String url;
private String name;
//构造器
public TestThread4(String url, String name){
this.url = url;
this.name = name;
}
@Override
public void run() {
WebDownloader webDownloader = new WebDownloader();
webDownloader.downloader(url,name);
System.out.println("下载了文件名为:"+name);
}
public static void main(String[] args) {
TestThread4 test1 = new TestThread4("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwx3.sinaimg.cn%2Fmw690%2F006a7Fqsly1h6l1m1o2v8j31o02yo7wi.jpg&refer=http%3A%2F%2Fwx3.sinaimg.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1667102238&t=2663277ec5f007ad772e6cface75ec86","1.png");
TestThread4 test2 = new TestThread4("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fbkimg.cdn.bcebos.com%2Fpic%2F37d12f2eb9389b504fc209f70a7af2dde71190efc04c&refer=http%3A%2F%2Fbkimg.cdn.bcebos.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1667102500&t=ce4bf55425348082daa6f6e5132a8920","2.png");
TestThread4 test3 = new TestThread4("https://img1.baidu.com/it/u=4282593950,4216695015&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=515","3.png");
TestThread4 test4 = new TestThread4("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_bt%2F0%2F11324654676%2F1000.jpg&refer=http%3A%2F%2Finews.gtimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1667102566&t=e9f6e5a7c126a283489789301cacb584","4.png");
Thread t1 = new Thread(test1);
Thread t2 = new Thread(test2);
Thread t3 = new Thread(test3);
Thread t4 = new Thread(test4);
t1.start();
t2.start();
t3.start();
t4.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方法出问题");
}
}
}
推荐使用Runnable实现方式。
多线程同时操作一个方法
并发问题: 多个线程操作一个对象时,会产生并发问题。
package com.ssl.demo01;
//多线程同时操作一个对象
//买火车票的例子
public class TestThread5 implements Runnable{
//票数
private int ticketNums = 10;
@Override
public void run() {
while (true) {
if(ticketNums==0)
break;
//模拟延时,会存在并发问题
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
//得到当前线程的名字
System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNums--+"票");
}
}
public static void main(String[] args) {
TestThread5 tickle = new TestThread5();
Thread thread1 = new Thread(tickle,"小明");
Thread thread2 = new Thread(tickle,"大黄");
Thread thread3 = new Thread(tickle,"老师");
Thread thread4 = new Thread(tickle,"黄牛党");
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}
龟兔赛跑
package com.ssl.demo01;
public class Race implements Runnable{
//胜利者
private static String winner;
@Override
public void run() {
for (int i = 0; i < 100; i++) {
//判断比赛是否结束
boolean flag = gameOver(i);
if(flag){
break;
}
//模拟兔子睡觉
if(Thread.currentThread().getName()=="兔子" && (i+1)%50==0) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
System.out.println(Thread.currentThread().getName()+"跑了"+i+"步");
}
}
//判断是否完成比赛
private boolean gameOver(int steps){
if(winner!=null){
return true;
}else{
if (steps >= 99){
winner = Thread.currentThread().getName();
System.out.println("胜利者"+winner);
return true;
}
return false;
}
}
public static void main(String[] args) {
Race race = new Race();
new Thread(race,"兔子").start();
new Thread(race,"乌龟").start();
}
}
Callable
步骤:(了解即可)
- 实现Callable接口,需要返回值类型
- 重写call方法,需要抛出异常
- 创建目标对象
- 创建执行服务:
ExecutoService ser = Exectors.newFixedThreadPool(数量);
- 提交执行:
Future<Boolean> result1 = ser.submit(t1);
- 获取结果
boolean r1 = result1.get();
- 关闭服务
ser.shutdownNow();
实现下载图片
package com.ssl.demo01;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.concurrent.*;
//线程创建方法3 实现callable接口
/**
*
*/
public class TestCallable implements Callable<Boolean> {
private String url;
private String name;
@Override
public Boolean call(){
WebDownloader2 webDownloader = new WebDownloader2();
webDownloader.downloader(url,name);
System.out.println("下载了文件名为:"+name);
return true;
}
//构造器
public TestCallable(String url, String name){
this.url = url;
this.name = name;
}
public static void main(String[] args) {
TestCallable test1 = new TestCallable("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwx3.sinaimg.cn%2Fmw690%2F006a7Fqsly1h6l1m1o2v8j31o02yo7wi.jpg&refer=http%3A%2F%2Fwx3.sinaimg.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1667102238&t=2663277ec5f007ad772e6cface75ec86","1.png");
TestCallable test2 = new TestCallable("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fbkimg.cdn.bcebos.com%2Fpic%2F37d12f2eb9389b504fc209f70a7af2dde71190efc04c&refer=http%3A%2F%2Fbkimg.cdn.bcebos.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1667102500&t=ce4bf55425348082daa6f6e5132a8920","2.png");
TestCallable test3 = new TestCallable("https://img1.baidu.com/it/u=4282593950,4216695015&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=515","3.png");
TestCallable test4 = new TestCallable("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_bt%2F0%2F11324654676%2F1000.jpg&refer=http%3A%2F%2Finews.gtimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1667102566&t=e9f6e5a7c126a283489789301cacb584","4.png");
//创建执行服务
ExecutorService ser = Executors.newFixedThreadPool(4);
//提交执行
Future<Boolean> result1 = ser.submit(test1);
Future<Boolean> result2 = ser.submit(test2);
Future<Boolean> result3 = ser.submit(test3);
Future<Boolean> result4 = ser.submit(test4);
//获取结果
try {
boolean rs1 = result1.get();
boolean rs2 = result2.get();
boolean rs3 = result3.get();
boolean rs4 = result4.get();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
//关闭服务
ser.shutdownNow();
}
}
//下载器
class WebDownloader2{
//下载方法
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方法出问题");
}
}
}
标签:java,String,Thread,--,线程,new,com,public
From: https://www.cnblogs.com/ssl-study/p/16745944.html