java多线程
继承类Thread和调用接口Runnable(推荐)的区别
下面是一个多线程的例子
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class TestThread extends Thread{
private String url;
private String name;
public TestThread(String url,String name){
this.url=url;
this.name=name;
}
//run方法就是线程的执行体
@Override
public void run() {
wedownloader wedownloader = new wedownloader();
wedownloader.downloader(url,name);
System.out.println("下载的文件名为"+name);
}
public static void main(String[] args) {
TestThread testThread = new TestThread("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fc-ssl.duitang.com%2Fuploads%2Fitem%2F202003%2F05%2F20200305082926_wosuw.thumb.1000_0.jpg&refer=http%3A%2F%2Fc-ssl.duitang.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1639273600&t=cf0604d746048a8bc47a919f4692f844","喜羊羊");
TestThread testThread2 = new TestThread("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.puchedu.cn%2Fuploads%2F2%2F26%2F3509169014%2F652515027.jpg&refer=http%3A%2F%2Fimg.puchedu.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1639273765&t=bd7b9d6e5e44f5a969031418b906313f","美羊羊");
TestThread testThread3 = new TestThread("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Finews.gtimg.com%2Fnewsapp_match%2F0%2F11500203347%2F0.jpg&refer=http%3A%2F%2Finews.gtimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1639273814&t=e14f23fab58f6d40d97ec48cf2877962","懒洋洋");
//start方法就是线程的启动
testThread.start();
testThread2.start();
testThread3.start();
}
class wedownloader{
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出现问题");
}
}
}
}
可以发现多个线程是没有先后顺序,一起执行的。
线程中的并发问题
//多个线程同时操作同一个对象
//例如买火车票的操作,多个人抢票造成了线程的混乱(并发问题)
public class TestThread3 implements Runnable{
private int ticketNums = 10;
@Override
public void run() {
while (true){
if (ticketNums<=0){
break;
}
System.out.println(Thread.currentThread().getName()+"拿到了第"+ticketNums--+"张票");
}
}
public static void main(String[] args) {
TestThread3 testThread3 = new TestThread3();
new Thread(testThread3,"小明").start();
new Thread(testThread3,"老师").start();
new Thread(testThread3,"黄牛").start();
}
}
有的人会拿到一样的票
模拟龟兔赛跑
import com.google.inject.internal.cglib.core.$Signature;
//模拟龟兔赛跑
public class Race implements Runnable{
//胜利者
private static String winner;
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
//模拟兔子睡觉
if (Thread.currentThread().getName().equals("兔子")&&i%50==0){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//判断比赛是否结束
boolean flag=gameOver(i);
if (flag){
break;
}
System.out.println(Thread.currentThread().getName()+"--->跑了"+i+"步");
}
}
private boolean gameOver(int step){
if (winner!=null){
return true;
}{
if (step>=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();
}
}
静态代理
public class StaticProxy {
public static void main(String[] args) {
WeddingCompany weddingCompany = new WeddingCompany(new You());
weddingCompany.HappyMarry();
}
}
interface Marry{
void HappyMarry();
}
class You implements Marry{
@Override
public void HappyMarry() {
System.out.println("结婚了结婚了");
}
}
class WeddingCompany implements Marry{
private Marry target;
public WeddingCompany(Marry target){
this.target=target;
}
@Override
public void HappyMarry() {
before();
this.target.HappyMarry();
after();
}
private void before() {
System.out.println("结婚前,布置现场");
}
private void after() {
System.out.println("结婚后,入洞房");
}
}
Lamda表达式:狂神说视频
线程的停止
public class TestStop implements Runnable{
private boolean flag=true;
@Override
public void run() {
int i = 0;
while (flag){
System.out.println("run...Thread"+i++);
}
}
public void stop(){
this.flag=false;
}
public static void main(String[] args) {
TestStop testStop = new TestStop();
new Thread(testStop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main"+i);
if (i==900){
testStop.stop();
System.out.println("线程停止");
}
}
}
}
线程休眠
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestSleep2 {
public static void main(String[] args) {
//打印当前系统时间
Date startTime = new Date(System.currentTimeMillis());
while (true){
try {
Thread.sleep(100);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
startTime=new Date(System.currentTimeMillis());//获取当前系统时间
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
//模拟倒计时
public static void tenDown() throws InterruptedException{
int num=10;
while (true){
Thread.sleep(1000);
System.out.println(num--);
if (num<=0){
break;
}
}
}
}
线程礼让
- 礼让线程,能让当前正在执行的线程暂停,但不阻塞
- 将线程从运行状态转为就绪状态
- 让CPU重新调度,礼让不一定成功!看CPU心情
public class TestYield {
public static void main(String[] args) {
MyYield myYield = new MyYield();
new Thread(myYield,"a").start();
new Thread(myYield,"b").start();
}
}
class MyYield implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"线程开始执行----");
Thread.yield();//礼让
System.out.println(Thread.currentThread().getName()+"线程停止执行-----");
}
}
礼让成功状态
礼让失败状态
线程的强制执行(插队)
不建议使用,因为可能会造成阻塞
public class TestJoin implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("线程vip来了"+i);
}
}
public static void main(String[] args) throws InterruptedException {
TestJoin testJoin = new TestJoin();
Thread thread = new Thread(testJoin);
for (int i = 0; i < 1000; i++) {
if (i==200){
thread.start();
thread.join();//插队
}
System.out.println("main"+i);
}
}
}
线程的状态
线程的优先级
线程同步(重要)
这是一个很重要的内容
在Buy方法的前面加入了syncronized这样就可以进行同步,就不会出现两人同时抢到一张票的情况。
//这就是一种不安全的方式,会存在两个人抢到了同一张票的情况
public class UnsafeTicket {
public static void main(String[] args) {
BuyTickert buyTickert = new BuyTickert();
new Thread(buyTickert,"男人").start();
new Thread(buyTickert,"女人").start();
new Thread(buyTickert,"黄牛").start();
}
}
class BuyTickert implements Runnable{
//票
private int ticketNums =10;
boolean flag = true;
@Override
public void run() {
//买票
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//synchronized 同步方法,锁的是this
private synchronized void buy() throws InterruptedException {
if (ticketNums<=0){
flag= false;
return;
}
Thread.sleep(100);
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}
死锁
线程池
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestPool {
public static void main(String[] args) {
//1.创建服务,创建线程池
//newFixedThreadPool 参数为:线程池大小
ExecutorService service= Executors.newFixedThreadPool(10);
//执行
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
//2.关闭链接
service.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
内容总结(线程执行的三种方式)
public class ThreadNew {
public static void main(String[] args) {
new MyThread1().start();
new Thread(new MyThread2()).start();
FutureTask<Integer> futureTask=new FutureTask<Integer>(new MyThread3());
new Thread(futureTask).start();
try {
Integer integer = futureTask.get();
System.out.println(integer);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
//1.继承Thread类
class MyThread1 extends Thread{
@Override
public void run() {
System.out.println("11111111111111");
}
}
//2.实现Runnable接口
class MyThread2 implements Runnable{
@Override
public void run() {
System.out.println("22222222222222222");
}
}
//3.实现Callable接口
class MyThread3 implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("333333333333");
return 100;
}
}
这些笔记都是参照狂神的视频做的嘿嘿嘿。觉得讲的还是可以的。狂老师牛逼!