引入包
import java.lang.Thread;
多线程定义
执行过程
创建线程
继承Thread
1.引入包Thread
2.自定义子类,extends Thread
3.重写run方法
import java.lang.Thread;
public class MyThread extends Thread{
public void run() {
for(int i = 0;i < 5;i++) {
System.out.println("MyThread: "+i);
}
}
}
调用
MyThread m1 = new MyThread();
m1.start();
实现Runnable接口
1.implements Runnable接口
2.重写run方法
public class MyRunnable implements Runnable{
public void run() {
for(int i = 0;i < 5;i++) {
System.out.println("MyRunnable: "+i);
}
}
}
1.创建Runnable对象
2.加入Thread对象
3.启动线程
MyRunnable f2 = new MyRunnable();
Thread m2 = new Thread(f2);
m2.start();
Callable和Future
import java.util.concurrent.Callable;
public class MyCallable implements Callable<String>{
public String call() {
for(int i = 0;i < 5;i++) {
System.out.println("MyCallable: "+i);
}
return "Callable";
}
}
//创建 Callable 实现类的实例
MyCallable m3 = new MyCallable();
//使用 FutureTask 类来包装 Callable 对象
FutureTask f1 = new FutureTask(m3);//Future包装
//3. 使用 FutureTask 对象作为 Thread 对象的 target 创建并启动新线程。
new Thread(f1).start();//创建线程,启动
//4. 调用 FutureTask 对象的 get() 方法来获得子线程执行结束后的返回值。
System.out.println(f1.get());
几个方法
线程同步
银行卡100元,两个人去同时取这100元,会冲突
示例
package Exer3;
import java.lang.Thread;
public class Text {
public static void main(String []args) {
//货架上16个
Product p = new Product();
//生产商品100个
//生产进程,一个厂家
new Thread(()->{
for(int i = 0;i < 100;i++) {//100商品
p.create();
}
}
).start();
//顾客 ? 个
//消费进程,一个消费者
new Thread(()->{
while(true) {
p.cost();
}
}).start();
//消费进程,一个消费者
new Thread(()->{
while(true) {
p.cost();
}
}).start();
}
}
package Exer3;
public class Product {
int num = 0;
Product(){
}
public synchronized void create() {
try {
if(num>=0&&num<16) {
num++;
System.out.println("生产!");
Thread.sleep(1000);
this.notifyAll();
this.wait();
}else {
System.out.println("货架满了");
this.notifyAll();
this.wait();
}
}catch(Exception e) {
e.printStackTrace();
}
}
public synchronized void cost() {
try {
if(num>0) {
num--;
System.out.println("买走了!");
Thread.sleep(1000);
this.notifyAll();
this.wait();
}else {
System.out.println("货架空了,需要生产");
this.notifyAll();
this.wait();
}
}catch(Exception e) {
e.printStackTrace();
}
}
}