多线程
Thread
-
自定义线程类继承Thread类。
-
-
创建线程对象,调用start()方法启动线程。
package thread;
//创建线程方式1:继承Thread类,重写run方法,调用start开启线程
//总结:注意,线程开启不一定立即执行,由CPU调度执行。
public class TestThread1 extends Thread {
public void run() {
//run方法线程体
for (int i = 0; i < 20; i++) {
System.out.println("我已经学了"+i+"遍了");
}
}
}
package thread;
public class TestStart {
public static void main(String[] args) {
//main线程,主线程
//创建一个线程对象
TestThread1 testThread1 = new TestThread1();
//调用start方法
testThread1.start();
for (int i = 0; i < 200; i++) {
System.out.println("我在学习另一个"+i);
}
}
}
package thread;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URL;
//练习Thread,实现多线程同步下载图片
public class TestThread2 extends Thread{
private String url;//网络图片地址
private String name;//保存的文件名
public TestThread2(String url, String name) {
this.url = url;
this.name = name;
}
//下载图片线程的执行体
public void run() {
WebDownLoader webDownLoader = new WebDownLoader();
webDownLoader.downloader(url,name);
System.out.println("下载了文件名为:"+name);
}
public static void main(String[] args) {
TestThread2 t1 = new TestThread2("https://img.yalayi.net/d/file/2020/07/02/56acd168bcfa628357171e2238fc706f.jpg", "1.jpg");
TestThread2 t2 = new TestThread2("https://img.yalayi.net/d/file/2020/07/02/683b5c42ff95dabf391fe6206a517bb7.jpg", "2.jpg");
TestThread2 t3 = new TestThread2("https://img.yalayi.net/d/file/2020/07/02/3684e97a6c2ed42119f4ae9d6185261d.jpg", "3.jpg");
t1.start();
t2.start();
t3.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异常!");
}
}
}
Runnable
定义MyRunnable类实现Runnable接口。
实现run()方法,编写线程执行体。
创建线程对象,调用start()方法启动线程。
package thread;
//创建线程方式2:实现runnable接口,重写run方法,执行线程需要丢入runnable接口实现类,调用start方法。
public class TestThread3 implements Runnable {
public void run() {
//run方法线程体
for (int i = 0; i < 200; i++) {
System.out.println("A:"+i);
}
}
public static void main(String[] args) {
//创建runnable接口的实现类对象
TestThread3 testThread3 = new TestThread3();
//创建线程对象,通过线程对象来开启线程。
new Thread(testThread3).start();
for (int i = 0; i < 100; i++) {
System.out.println("B:"+i);
}
}
}
Runnable接口和Thread类类似,只是在Runnable使用时需要new一个Thread对象,将Runnable实现类的实例化作为参数传入,然后点start。
推荐使用Runnable接口,避免单继承局限性,灵活方便,方便同一个对象被对各线程使用。
package thread;
import javax.swing.*;
public class Race implements Runnable {
//胜利者的名字
private static String winner;
public void run() {
for (int i = 0; i <= 100; i++) {
if (Thread.currentThread().getName().equals("兔子") && i%10==0){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//判断比赛是否结束
if (gameOver(i)) {
break;
}
System.out.println(Thread.currentThread().getName() + "跑了" + 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();
}
}
STOP线程
package thread;
//测试stop
//1. 建议线程正常停止:利用次数,不建议死循环。
//2.建议使用标志位:设置一个标志位。
//3.不要使用stop或者destroy等过时或者JDK不建议使用的方法
public class TestStop implements Runnable{
private Boolean flag=true;
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("线程终止了!");
}
}
}
}
线程优先级
使用一下方式改变或获取线程优先级:
getPriority()。setPriority(int xxx)
优先级的设定建议在start()调度前。
同时优先级低只意味着获得调度的概率低,并不是优先级低就不会被调用了,这都是看CPU的调度。
Lock
package thread;
import javax.swing.*;
import java.util.concurrent.locks.ReentrantLock;
public class TestThread4 implements Runnable {
//票数
private int num = 10;
//定义lock锁
private final ReentrantLock lock=new ReentrantLock();
public void run() {
while (true) {
try {
lock.lock();
//模拟延时
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (num == 0) {
break;
}
System.out.println(Thread.currentThread().getName() + "拿到了第" + num-- + "张票");
} finally {
//解锁
lock.unlock();
}
}
}
public static void main(String[] args) {
TestThread4 testThread4 = new TestThread4();
new Thread(testThread4, "小明").start();
new Thread(testThread4, "小红").start();
new Thread(testThread4, "黄牛").start();
}
}
# 多线程
---
## Thread
---
* 自定义线程类继承Thread类。* 重写run()方法,编写线程执行体。* 创建线程对象,调用start()方法启动线程。
```javapackage thread;
//创建线程方式1:继承Thread类,重写run方法,调用start开启线程//总结:注意,线程开启不一定立即执行,由CPU调度执行。public class TestThread1 extends Thread { @Override public void run() { //run方法线程体 for (int i = 0; i < 20; i++) { System.out.println("我已经学了"+i+"遍了"); } }
}```
```javapackage thread;
public class TestStart { public static void main(String[] args) { //main线程,主线程
//创建一个线程对象 TestThread1 testThread1 = new TestThread1();
//调用start方法 testThread1.start();
for (int i = 0; i < 200; i++) { System.out.println("我在学习另一个"+i); } }}```
```javapackage thread;
import org.apache.commons.io.FileUtils;
import java.io.File;import java.io.IOException;import java.net.URL;
//练习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 t1 = new TestThread2("https://img.yalayi.net/d/file/2020/07/02/56acd168bcfa628357171e2238fc706f.jpg", "1.jpg"); TestThread2 t2 = new TestThread2("https://img.yalayi.net/d/file/2020/07/02/683b5c42ff95dabf391fe6206a517bb7.jpg", "2.jpg"); TestThread2 t3 = new TestThread2("https://img.yalayi.net/d/file/2020/07/02/3684e97a6c2ed42119f4ae9d6185261d.jpg", "3.jpg");
t1.start(); t2.start(); t3.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异常!"); } }}```
## Runnable
---
定义MyRunnable类实现Runnable接口。
实现run()方法,编写线程执行体。
创建线程对象,调用start()方法启动线程。
```javapackage thread;
//创建线程方式2:实现runnable接口,重写run方法,执行线程需要丢入runnable接口实现类,调用start方法。public class TestThread3 implements Runnable {
@Override public void run() { //run方法线程体 for (int i = 0; i < 200; i++) { System.out.println("A:"+i); } }
public static void main(String[] args) { //创建runnable接口的实现类对象 TestThread3 testThread3 = new TestThread3();
//创建线程对象,通过线程对象来开启线程。 new Thread(testThread3).start();
for (int i = 0; i < 100; i++) { System.out.println("B:"+i); } }}```
Runnable接口和Thread类类似,只是在Runnable使用时需要new一个Thread对象,将Runnable实现类的实例化作为参数传入,然后点start。
推荐使用Runnable接口,避免单继承局限性,灵活方便,方便同一个对象被对各线程使用。
```javapackage thread;
import javax.swing.*;
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%10==0){ try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } }
//判断比赛是否结束 if (gameOver(i)) { break; }
System.out.println(Thread.currentThread().getName() + "跑了" + 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(); }}```
### STOP线程
---
```javapackage thread;
//测试stop//1. 建议线程正常停止:利用次数,不建议死循环。//2.建议使用标志位:设置一个标志位。//3.不要使用stop或者destroy等过时或者JDK不建议使用的方法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("线程终止了!"); } } }}```
### 线程优先级
---
使用一下方式改变或获取线程优先级:
getPriority()。setPriority(int xxx)
优先级的设定建议在start()调度前。
同时优先级低只意味着获得调度的概率低,并不是优先级低就不会被调用了,这都是看CPU的调度。
### Lock
---
```javapackage thread;
import javax.swing.*;import java.util.concurrent.locks.ReentrantLock;
public class TestThread4 implements Runnable {
//票数 private int num = 10;
//定义lock锁 private final ReentrantLock lock=new ReentrantLock();
@Override public void run() { while (true) { try { lock.lock(); //模拟延时 try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
if (num == 0) { break; }
System.out.println(Thread.currentThread().getName() + "拿到了第" + num-- + "张票");
} finally { //解锁 lock.unlock(); } } }
public static void main(String[] args) { TestThread4 testThread4 = new TestThread4();
new Thread(testThread4, "小明").start(); new Thread(testThread4, "小红").start(); new Thread(testThread4, "黄牛").start(); }}```

浙公网安备 33010602011771号