Java多线程1
发布日期:2021-04-30 21:06:06 浏览次数:117 分类:精选文章

本文共 2444 字,大约阅读时间需要 8 分钟。

Java???????

???????

????????????????????????????????????????????????????????????????????????????????????

????????

  • ????????????????????????????????
  • ????????????????????????
?? ?? ??
??????? ? ?
?????? ? ?
???? ???? ????

?????????

????????????????????????????????????????????????????????????????

????????

  • ???????????????????
  • ??????????CPU????????????

Java????????

Java?????????????????????????

1. ?? Thread ?

???? Thread ??????????? run ?????????

public class MyThread extends Thread {
@Override
public void run() {
String threadName = Thread.currentThread().getName();
for (int i = 1; i <= 100; i++) {
System.out.println(threadName + "i=" + i);
}
}
}

2. ?? Runnable ??

???? Runnable ????????run ??????????

public class DoxThread implements Runnable {
@Override
public void run() {
String threadName = Thread.currentThread().getName();
for (int i = 1; i <= 100; i++) {
System.out.println(threadName + "i=" + i);
}
}
}
public class TestMain {
public static void main(String[] args) {
DoxThread doxThread = new DoxThread();
Thread thread1 = new Thread(doxThread);
Thread thread2 = new Thread(doxThread);
thread1.start();
thread2.start();
}
}

3. Callable ? Future ??

Callable ??????????????Future ??????????????

public class TestThread implements Callable
{
@Override
public String call() throws Exception {
String name = Thread.currentThread().getName();
for (int i = 1; i <= 100; i++) {
System.out.println(name + "-i-" + i);
}
return name + "????";
}
}
public class TestMain {
public static void main(String[] args) throws Exception {
TestThread testThread = new TestThread();
FutureTask
futureTask1 = new FutureTask<>(testThread);
FutureTask
futureTask2 = new FutureTask<>(testThread);
Thread thread1 = new Thread(futureTask1);
Thread thread2 = new Thread(futureTask2);
thread1.start();
thread2.start();
String result1 = futureTask1.get();
System.out.println("????????" + result1);
String result2 = futureTask2.get();
System.out.println("????????" + result2);
}
}

4. ????????

??????????????????????????????

???????????

???????????????????????????????????????????????????

?????????????????????????????????????

上一篇:插件化框架解读之android系统服务实现原理,面试总结
下一篇:centos7.4搭建ftp服务器

发表评论

最新留言

能坚持,总会有不一样的收获!
[***.219.124.196]2026年06月04日 20时19分54秒