两个线程A和B,任务都是打印当前时间,要求编码实现:线程A和B同时启动后,以先A后B的方式任务交叉执行10次。

方式一:

package com.james.test;
import java.util.Date;
public class ThreadTest
{

static int n = 0;
Thread A = null;
Thread B = null;

static void Print()
{
System.out.println("ID: " + (n + 1) + " Thread id:"
+ Thread.currentThread().getId() + "  name:"
+ Thread.currentThread().getName() + "  "
+  new Date().toLocaleString());
}

class myrunable implements Runnable
{


public myrunable()
{
A = new Thread(this);
B = new Thread(this);
}

public void start()
{
A.start();
B.start();
}

@Override
public void run()
{
for (int i = 0; i < 10; i++)
{
synchronized (this) {

Thread t = Thread.currentThread();

if (n==0&&t != A)  //首次必须是线程A执行
return;
Print();
                    n++;
                    notifyAll(); //唤醒另一个等待的线程
                   
                    try
                    {
                     if(i<9)//不是最后一次
     wait();//当前线程进入等待状态,释放同步锁
     }
                    catch (InterruptedException e)
     {
   
     e.printStackTrace();
     }
}
}

}
};

public static void main(String[] args) throws InterruptedException
{
myrunable r = new ThreadTest().new myrunable();
r.start();
Thread.sleep(5000);
}
}

方式二:

package test;

import java.text.SimpleDateFormat;
import java.util.Date;

public class ThreadEx {
private Object o = new Object(); // 共享资源
private boolean flag = true; // 互斥信号量

class Thread1 extends Thread {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:ms");
public void run() {
synchronized (o) { // 线程同步
for (int i = 1; i <= 10; i++) {
  System.out.println("New thread-->A:" + sdf.format(new Date()));
  o.notify(); // 唤醒另外一个进程
  if(flag){
     flag = false;
     try {
         o.wait(); // 当前线程等待
     } catch (InterruptedException e) {
          e.printStackTrace();
     }
  }
}
System.out.println("Thread-->A complete");
}
}
}

class Thread2 extends Thread {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:ms");

public void run() {
synchronized (o) { // 线程同步
for (int i = 1; i <= 10; i++) {
  System.out.println("New thread-->B:" + sdf.format(new Date()));
  o.notify(); // 唤醒另外一个进程
  if(!flag){
    flag = true;
     try {
           if(i != 10){
             o.wait(); // 当前线程等待
           }
    } catch (InterruptedException e) {
            e.printStackTrace();
    }
}
}
System.out.println("Thread-->B complete");
}
}
}
public void show(){
     new Thread1().start();
     new Thread2().start();
}

public static void main(String[] args) {
     ThreadEx t = new ThreadEx();
     t.show();
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值