多线程1
一个进程可以有多个线程
process、thread
main()主线程还可以运行其他线程
线程创建
继承Thread类、实现Runnable(接口)、实现Callable(接口)
继承Thread,重写()run方法
线程开启不一定立即执行,由CPU调用执行
package thread;
//创建线程方式一:继承Thread类,重写run()方法,调用start开启线程
public class Demo1 extends Thread{
@Override
//run方法线程体
public void run() {
for (int i = 0; i < 1001; i++) {
System.out.println("执行" + i);
}
}
//main方法主线程
public static void main(String[] args) {
//创建线程对象,
Demo1 demo1 = new Demo1();
//调用run方法是先执行run方法再执行下面的循环,
// 而调用start方法是两个线程同时执行,系统调用的时间片有先后而已
demo1.run();
for (int i = 0; i < 1001; i++) {
System.out.println("hello world!" + i);
}
}
}
多线程文件下载
package thread;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class WebFileDownLoader {//网页文件下载器
public void downFile(String name,String url){
File file = new File(name);
try {
FileUtils.copyURLToFile(new URL(url),file);//使用别人封装好的1类实现
} catch (IOException e) {//捕获异常,判断是有在此处出现错误
System.out.println(e + "WebFileDownLoader类downFile方法");
}
}
}
package thread;
public class Demo2 extends Thread{//使用线程实现多图片同时下载
private String name;
private String url;
public Demo2(){ }
public Demo2(String name, String url) {
this.name = name;//文件名
this.url = url;//url名
}
@Override
public void run() {
WebFileDownLoader webFileDownLoader = new WebFileDownLoader();
webFileDownLoader.downFile(name,url);
System.out.println(name);
}
/*
* D:\ideaProject\Test\javaSE\jichuyufa\resources\3.jpg
D:\ideaProject\Test\javaSE\jichuyufa\resources\2.jpg
D:\ideaProject\Test\javaSE\jichuyufa\resources\4.jpg
* 线程同时进行
* */
public static void main(String[] args) {
Demo2 demo2 = new Demo2("D:\\ideaProject\\Test\\javaSE\\jichuyufa\\resources\\2.jpg" ,
"https://tse4-mm.cn.bing.net/th/id/OIP-C.owpbNjuu23xkyc4yrX9BDQHaEo?pid=ImgDet&rs=1");
Demo2 demo3 = new Demo2("D:\\ideaProject\\Test\\javaSE\\jichuyufa\\resources\\3.jpg" ,
"https://desk-fd.zol-img.com.cn/t_s960x600c5/g1/M0B/03/06/ChMljl402K6IOTZbAARWayFg6S4AAQJPwFhuRIABFaD752.jpg");
Demo2 demo4 = new Demo2("D:\\ideaProject\\Test\\javaSE\\jichuyufa\\resources\\4.jpg" ,
"https://pic.3gbizhi.com/2019/0928/20190928012439343.jpg");
demo2.start();
demo3.start();
demo4.start();
new WebFileDownLoader().downFile("D:\\ideaProject\\Test\\javaSE\\jichuyufa\\resources\\5.jpg",
"https://ts1.cn.mm.bing.net/th/id/R-C.987f582c510be58755c4933cda68d525?r" +
"ik=C0D21hJDYvXosw&riu=http%3a%2f%2fimg.pconline.com.cn%2fimages%2fupload%2fupc%2ftx%2fwallpaper%2f1305%" +
"2f16%2fc4%2f20990657_1368686545122.jpg&ehk=netN2qzcCVS4ALUQfDOwxAwFcy41oxC%2b0xTFvOYy5ds%3d&risl=&pid=ImgRaw&r=0");
}
}
实现runnable接口
定义一个类实现Runnable接口
实现run方法,编写线程体
创建线程对象,调用start方法启动线程,推荐使用,因为java单继承
package thread;
//创建线程方式二:实现Runnable接口,重写run()方法,执行线程需要1丢入runnable接口的实现类中,调用start开启线程
public class TestThread1 implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("执行Runnable" + i);
}
}
public static void main(String[] args) {
TestThread1 testThread1 = new TestThread1();
Thread thread = new Thread(testThread1);
thread.start();
}
}
线程并发问题
package thread;
//线程并发,操作同一对象会出现紊乱
public class Demo3 implements Runnable{
public int ticketNum = 20;
@Override
public void run() {
while (true) {
try {
Thread.sleep(100);
if (ticketNum == 0) {
break;
}else
System.out.println(Thread.currentThread().getName() + "拿到了第" + ticketNum-- + "张票");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Demo3 demo3 = new Demo3();//打印结果出现了紊乱
new Thread(demo3,"A").start();
new Thread(demo3,"B").start();
new Thread(demo3,"C").start();
}
}
龟兔赛跑3
package thread;
//龟兔赛跑
public class Demo4 implements Runnable{
private static String winner;
public boolean gameOver(int steps){
if (winner!= null){
return true;
}else {
if (steps >= 9999){
winner = Thread.currentThread().getName();
System.out.println(winner);
return true;
}
}
return false;
}
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
if (Thread.currentThread().getName().equals("兔子")){
i+=999;
try {
System.out.println(Thread.currentThread().getName() + "============跑了" + i + "步");
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
boolean flag = gameOver(i);
if (flag){
break;
}else if(Thread.currentThread().getName().equals("乌龟"))
System.out.println(Thread.currentThread().getName() + "跑了" + i + "步");
}
}
public static void main(String[] args) {
Demo4 demo4 = new Demo4();
new Thread(demo4,"兔子").start();
new Thread(demo4,"乌龟").start();
}
}
Callable
package thread;
import java.util.concurrent.*;
public class CallAble implements Callable<Boolean> {
private String name;
private String url;
public CallAble(){ }
public CallAble(String name, String url) {
this.name = name;//文件名
this.url = url;//url名
}
@Override
public Boolean call() throws Exception {
WebFileDownLoader webFileDownLoader = new WebFileDownLoader();
webFileDownLoader.downFile(this.name,this.url);
System.out.println(this.name);
return true;
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
CallAble demo2 = new CallAble("D:\\ideaProject\\Test\\javaSE\\jichuyufa\\resources\\2.jpg" ,
"https://tse4-mm.cn.bing.net/th/id/OIP-C.owpbNjuu23xkyc4yrX9BDQHaEo?pid=ImgDet&rs=1");
CallAble demo3 = new CallAble("D:\\ideaProject\\Test\\javaSE\\jichuyufa\\resources\\3.jpg" ,
"https://desk-fd.zol-img.com.cn/t_s960x600c5/g1/M0B/03/06/ChMljl402K6IOTZbAARWayFg6S4AAQJPwFhuRIABFaD752.jpg");
CallAble demo4 = new CallAble("D:\\ideaProject\\Test\\javaSE\\jichuyufa\\resources\\4.jpg" ,
"https://pic.3gbizhi.com/2019/0928/20190928012439343.jpg");
//创建执行服务,创建新的线程池
ExecutorService threadPool = Executors.newFixedThreadPool(3);
//提交执行
Future<Boolean> submit1 = threadPool.submit(demo2);
Future<Boolean> submit2 = threadPool.submit(demo3);
Future<Boolean> submit3 = threadPool.submit(demo4);
//获取结果
System.out.println(Thread.currentThread().getName() + submit1.get());
System.out.println(Thread.currentThread().getName() + submit2.get());
System.out.println(Thread.currentThread().getName() + submit3.get());
//关闭服务
threadPool.shutdown();
}
}
静态代理模式
package thread;
/*静态代理模式:
真实对象和代理对象都要实现同一个接口
代理对象要代理真实角色
*代理对象可以做很多真实对象做不了的事
真实对象只需要做自己的事即可
* */
public class StaticProxy {
public static void main(String[] args) {
//new Restaurant(new Person("sang")).eatHappy();
Person sang = new Person("sang");//这个人,要吃饭
Restaurant restaurant = new Restaurant(sang);//去饭店吃饭
new Thread(() -> System.out.println("我饿了!")).start();//线程也是静态代理
restaurant.eatHappy();//饭店提供服务,你只管安心吃饭
}
}
interface eatFood{
void eatHappy();
}
//代理角色,帮助你提供能吃的食物
class Restaurant implements eatFood{
private Person target;
public Restaurant(Person person) {
this.target = person;
}
@Override
public void eatHappy() {
before();
this.target.eatHappy();
after();
}
private void after() {
System.out.println("收钱,找零");
}
private void before() {
System.out.println("厨师做饭,提供用餐环境");
}
}
//真实角色,去吃饭
class Person implements eatFood{
public String name;
public Person(String name) {
this.name = name;
}
@Override
public void eatHappy() {
System.out.println(this.name + " happy eat food!");
}
}
Lamda表达式
避免内部类定义过多
实质属于函数式编程的概念
(params)-> expression[表达式]
(params)-> statement[语句]
(params)-> {statements}
package thread;
public class LambdaTest implements Test{
public static void main(String[] args) {
//Lambda表达式
Test like = ()-> {
System.out.println("test5");
};
like.test();
//4.静态内部类
// Test1 test1 = new Test1();
// test1.test();
//1.实现类new LambdaTest().test();
//2.匿名内部类
/*new Test() {
@Override
public void test() {
System.out.println("test2");
}
}.test();*/
//3.局部内部类
/*class Like implements Test{
@Override
public void test() {
System.out.println("test3");
}
}
new Like().test();*/
}
//4.静态内部类
static class Test1 implements Test{
@Override
public void test() {
System.out.println("test4");
}
}
@Override
public void test() {
System.out.println("test1");
}
}
interface Test{
void test();
}
package thread;
import java.util.Scanner;
public class LambdaDemo1 {
//静态内部类
static class Lovely1 implements Test1{
@Override
public int add(int a, int b) {
int c = a + b;
System.out.println(c);
return c;
}
}
public static void main(String[] args) {
//匿名内部类
Test1 test1 = (int a,int b) ->{
int c = a + b;
System.out.println(c);
return 0;
};
test1.add(2,4);
//简化参数类型
test1 = (a,b) -> {
System.out.println( a+ b);
return a + b;
};
int c = test1.add(5,7);
System.out.println(c);
//new Lovely1().add(2,3);
// Lovely lovely = new Lovely();
// lovely.add(1,2);
}
}
//Lambda表达式前提是接口必须是函数式接口,只有一个方法的接口
interface Test1{
int add(int a,int b);
}
//外部类
class Lovely implements Test1{
@Override
public int add(int a, int b) {
int c = a + b;
System.out.println(c);
return c;
}
}
标签:void,System,println,new,多线程,public,out
From: https://www.cnblogs.com/1234sdg/p/17025526.html