Java多线程控制交替输出1和2
public static void main(String[] args) {
AtomicBoolean m = new AtomicBoolean();
m.set(true);
System.out.println("AtomicBoolean:" + m.get());
Thread1 thread1 = new Thread1();
Thread2 thread2 = new Thread2();
thread1.setMain(m);
thread2.setMain(m);
thread1.start();
thread2.start();
}
static class Thread1 extends Thread{
AtomicBoolean m ;
public void setMain(AtomicBoolean m){
this.m = m;
}
@Override
public void run() {
while(true){
try {
synchronized (m) {
System.out.println("tag1:" + m.get());
if(m.get()){
System.out.println("1");
m.set(false);
m.notify();
}
m.wait();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
static class Thread2 extends Thread{
AtomicBoolean m ;
public void setMain(AtomicBoolean m){
this.m = m;
}
@Override
public void run() {
while(true){
try {
synchronized (m) {
System.out.println("tag2:" + m.get());
if(!m.get()){
System.out.println("2");
m.set(true);
m.notify();
}
m.wait();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
本文标题:Java多线程控制交替输出1和2
本文链接:https://www.haomeiwen.com/subject/areywttx.html
网友评论