JAVA多线程---两个线程交替运行

1 篇文章 0 订阅
0 篇文章 0 订阅
/**
* 两个线程交替执行,a线程打印123,b线程打印456 和打印次数,执行结果是123456 0 123456 1 123456 2 ......
* @author shangjie
*
*/
public class TwoThreadLock {

private static Object LOCK = new Object();
private static boolean flag = false;

public static void main(String[] args) {

Thread b = new Thread() {
public void run() {
for (int c = 0; c <= 100; c++) {
synchronized (LOCK) {
for (int i = 4; i <= 6; i++) {
System.out.print(i);
}
System.out.print(" " + c);
System.out.println();
if(flag){
flag = false;
LOCK.notify();
if (c < 100) {
try {
LOCK.wait();

} catch (InterruptedException e) {
e.printStackTrace();
}
}

}
}

}
}
};

Thread a = new Thread() {
public void run() {
for (int c = 0; c <= 100; c++) {
synchronized (LOCK) {
for (int i = 1; i <= 3; i++) {
System.out.print(i);
}
if(!flag){
flag = true;
LOCK.notify();//在这里虽然唤醒了另一个线程b,但锁并没有释放
if (c < 100) {
try {
LOCK.wait();//在wait后的瞬间线程b得到锁

} catch (InterruptedException e) {
e.printStackTrace();
}
}

}
}
}
}
};

a.start();
b.start();
}
}


package com.mfz.test;

public class TwoThread {

private static Object lock = new Object();
private static boolean flag = false;

public static void main(String[] args) {

Thread a = new Thread(){
public void run()
{
while(true)
{
synchronized(lock)
{
System.out.println("Thread1");

if(flag)
{
flag = false;
lock.notify();
try {
lock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


}
}
};

Thread b = new Thread(){
public void run()
{
while(true)
{
synchronized(lock)
{
System.out.println("Thread2");

if(!flag)
{
flag =true;
try {
lock.notify();
lock.wait();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}


}
}
};

a.start();
b.start();
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值