public class MyRun implements Runnable{
//自强
@Override
public void run() {
for (int i = 0; i < 100; i++) {
Thread thread = Thread.currentThread();//获取当前线程
System.out.println(thread.getName()+"nihao");
}
}
}
复制代码
public class demo2 {
public static void main(String[] args) {
//1.自己定义一个类实现Runnable接口
//2.重写里面的run方法
//3.创建自己类的对象
//4.创建一个Thread对象,并开启线程
MyRun mr=new MyRun();
Thread t1=new Thread(mr);
Thread t2=new Thread(mr);
t1.setName("线程1");
t1.start();
t2.setName("线程2");
t2.start();
}
}
3.利用Callable接口和Future接口方式实现
可以获得多线程执行的返回结果
复制代码
import java.util.concurrent.Callable;
public class MyCallable implements Callable<Integer>{
@Override
public Integer call() throws Exception {
int sum=0;
for (int i = 0; i <=100; i++) {
sum+=i;
}
return sum;
}
}
package ThreadDemo;
public class Desk {
/*
控制生产者消费者的执行
*/
//是否有面条 0有 1没有
public static int foodFlag=0;
//总个数
public static int count=10;
//上锁
public static Object lock=new Object();
}
复制代码
public class demo9 {
public static void main(String[] args) {
Cook c=new Cook();
Foodie f=new Foodie();
c.setName("厨师");
c.setName("吃货");
c.start();
f.start();
}
}
运行结果:
生产者消费者阻塞队列实现
复制代码
public class Cook2 extends Thread{
ArrayBlockingQueue<String> queue;
public Cook2(ArrayBlockingQueue<String>queue){
this.queue=queue;
}
@Override
public void run() {
while(true){
try {
queue.put("面条");
System.out.println("厨师放一碗面条");//这个是锁的外面
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
复制代码
public class Food2 extends Thread{
ArrayBlockingQueue<String> queue;
public Food2(ArrayBlockingQueue<String>queue){
this.queue=queue;
}
@Override
public void run() {
while(true){
try {
String food=queue.take();
System.out.println(food);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
复制代码
public class demo10 {
public static void main(String[] args) {
ArrayBlockingQueue<String>queue=new ArrayBlockingQueue<>(1);//创建容量为1的阻塞队列
Food2 food2=new Food2(queue);
Cook2 cook2=new Cook2(queue);
food2.start();
cook2.start();
}
}