public class thread {
public static void main(String[] args) {
// 两个线程的锁对象是同一个
thread tt = new thread();
JiClass jiClass = tt.new JiClass(tt);
OuClass ouClass = tt.new OuClass(tt);
new Thread(jiClass).start();
new Thread(ouClass).start();
}
// 用标志来控制那个线程开始
private boolean flag;
public class JiClass implements Runnable {
private thread t;
//构造函数
private JiClass(thread t) {
this.t = t;
}
@Override
public void run() {
int i = 1; //本线程打印奇数,则从1开始
while (i < 100) {
//两个线程的锁的对象只能是同一个object
synchronized (t) {
if (!t.flag) {
System.out.println("-----" + i);
i += 2;
t.flag = true;
t.notify();
} else {
try {
t.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public class OuClass implements Runnable {
private thread t;
private OuClass(thread t) {
this.t = t;
}
@Override
public void run() {
int i = 2;//本线程打印偶数,则从2开始
while (i <= 100)
//两个线程的锁的对象只能是同一个object
synchronized (t) {
if (t.flag) {
System.out.println("-----------" + i);
i += 2;
t.flag = false;
t.notify();
} else {
try {
t.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
import java.util.concurrent.atomic.AtomicInteger;
/**
* 交替打印奇偶数
*/
public class thread {
//让两个线程使用同一把锁。交替执行 。
//判断是不是奇数 如果是奇数进入奇数线程执行打印并加一。然后线程释放锁资源。然后让该线程等待
//判断是不是偶数,如果是偶数进入偶数线程执行打印并加一。然后线程释放锁资源。然后让该线程等待
private static AtomicInteger atomicInteger =new AtomicInteger(1);
public static void main(String[] args) {
Thread a=new Thread(new AThread());
Thread b=new Thread(new BThread());
a.start();
b.start();
}
//奇数线程
public static class AThread implements Runnable{
public void run() {
while(true){
synchronized (atomicInteger) {
if(atomicInteger.intValue()%2 !=0){
System.out.println("奇数线程:" + atomicInteger.intValue()
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
atomicInteger.getAndIncrement(); // 以原子方式将当前值加 1。
// 奇数线程释放锁资源
atomicInteger.notify();
//执行完操作后释放锁并进入等待
try {
atomicInteger.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
// 奇数线程等待
try {
atomicInteger.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
//偶数线程
public static class BThread implements Runnable{
public void run() {
while(true){
synchronized (atomicInteger) {
if(atomicInteger.intValue()%2 ==0){
System.out.println("偶数线程:"+ atomicInteger.intVal
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
atomicInteger.getAndIncrement(); // 以原子方式将当前值加 1
// 偶数线程释放锁资源
atomicInteger.notify();
//执行完操作后释放锁并进入等待
try {
atomicInteger.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}else{
try {
// 偶数线程等待
atomicInteger.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
}