public class Student {
private String name ;
private int age ;
public boolean flag;
public Student() {
super();
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
import cn.bipt.thread.entity.Student;
public class consumer implements Runnable {
private Student s;
public consumer(Student s){
this.s = s;
}
public void run() {
while(true){
synchronized (s) {
if(!s.flag){
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(s.getName() "---" s.getAge());
//修改标记
s.flag = false;
//唤醒线程
s.notify();
}
}
}
}
import cn.bipt.thread.entity.Student;
public class Product implements Runnable{
private Student s;
private int cycle = 10;
public Product(Student s){
this.s = s;
}
@Override
public void run() {
while(true){
synchronized (s) {
if(s.flag){
try {
s.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(cycle%2==0){
s.setName("陈建兵");
s.setAge(19);
cycle ;
}else{
s.setName("张晓天");
s.setAge(20);
cycle ;
}
//修改标记
s.flag = true;
//唤醒
s.notify();
}
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
Student s = new Student();
Product pro = new Product(s);
consumer con = new consumer(s);
Thread t1 = new Thread(pro);
Thread t2 = new Thread(con);
t1.start();
t2.start();
}
}
12.线程池
代码语言:javascript复制
public class ExecutorsDemo {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
pool.submit(new MyRunnable());
pool.submit(new MyRunnable());
}
}
13.定时器
代码语言:javascript复制
public class timerDemo {
public static void main(String[] args) {
//创建定时器对象
Timer t = new Timer();
t.schedule(new Mytask(), 3000);
}
}
class Mytask extends TimerTask{
@Override
public void run() {
System.out.println("beng,爆炸了");
}
}
//每隔几秒再炸
public class timerDemo {
public static void main(String[] args) {
//创建定时器对象
Timer t = new Timer();
//三秒后爆炸,然后两秒后再炸
t.schedule(new Mytask(), 3000,2000);
}
}
class Mytask extends TimerTask{
@Override
public void run() {
System.out.println("beng,爆炸了");
}
}