今天做一道关于线程的题目:力扣链接:https://leetcode.cn/problems/print-in-order/
要点:掌握线程的创建方法 sleep() 和notifyall()的定义及使用
运行成功截图
具体代码实现
package com.zjy.leetcode;
//
public class Anxupaixu {
public static void main(String[] args) {
Foo foo=new Foo();
Thread t1=new Thread(()-> {
try {
foo.first(()->System.out.println("first"));
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread t2=new Thread(()-> {
try {
foo.second(()->System.out.println("second"));
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread t3=new Thread(()-> {
try {
foo.third(()->System.out.println("third"));
} catch (InterruptedException e) {
e.printStackTrace();
}
});
t1.start();
t2.start();
t3.start();
}
}
class Foo {
private int count =1;
public Foo(){
}
public synchronized void first(Runnable printFirst) throws InterruptedException {
// printFirst.run() outputs "first". Do not change or remove this line.
printFirst.run();
count++;
notifyAll();
}
public synchronized void second(Runnable printSecond) throws InterruptedException {
while(this.count!=2){
wait();
}
this.count++;
notifyAll();
// printSecond.run() outputs "second". Do not change or remove this line.
printSecond.run();
}
public synchronized void third(Runnable printThird) throws InterruptedException {
while(this.count !=3){
wait();
}
// printThird.run() outputs "third". Do not change or remove this line.
printThird.run();
}
}
其中创建线程的方法是lamda 匿名内部类
thread 单继承实现 改写实例
public class Anxupaixu {
public static void main(String[] args) {
Foo foo=new Foo();
SomeThread1 t1=new SomeThread1();
t1.start();
SomeThread2 t2=new SomeThread2();
t2.start();
SomeThread3 t3=new SomeThread3();
t3.start();
}
}
class SomeThread1 extends Thread{
Foo foo=new Foo();
public void run(){
try {
foo.first(()->System.out.println("first"));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class SomeThread2 extends Thread{
Foo foo=new Foo();
public void run(){
try {
foo.first(()->System.out.println("2"));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class SomeThread3 extends Thread{
Foo foo=new Foo();
public void run(){
try {
foo.first(()->System.out.println("3"));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
照样通过