两个线程一个打印1,一个打印2,要求循环打印1212121212

两个线程一个打印1,一个打印2,要求循环打印121212

方法1:

分析问题

两个线程,可以想到的是多线程编程,共享变量,数据等,设想先让一个线程打印1,然后处于等待(wait)状态,接着另一个线程打印2,然后唤醒(notify)线程1,线程2再进入等待(wait)状态,线程1被唤醒后接着打印1,依次循环输出即可

代码

public class Test {
    static final Object object = new Object();
    public static void main(String[] args){
        //线程1
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 0;i<5;i++){
                    synchronized (object){
                        System.out.println("1");
                        object.notify(); //唤醒线程2
                        try {
                            object.wait();//线程1进入等待
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();
        //线程2
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 0;i<5;i++){
                    synchronized (object){
                        System.out.println("2");
                        object.notify();//唤醒线程1
                        try {
                            object.wait();//线程2进入等待
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();
  

结果:

1
2
1
2
1
2
1
2
1

2

方法2:

分析问题:

使用volatile保证数据的可见性,避免多线程访问同一个变量,它的值刷新不及时的问题;设想定义一个volatile修饰的boolean变量flag,当flag为true时,线程1打印1,同时修改flag的值,置为false,当flag为false时,线程2打印2,同时修改falg的值,置为true,依次循环即可

代码

public class Test {
    volatile static boolean flag = true;
    public static void main(String[] args){
        Thread t1 = new MyThread(1);
        Thread t2 = new MyThread(2);
        t1.start();
        t2.start();
    }

    static class MyThread extends Thread{
        int printValue;
        public MyThread(int printValue){
            this.printValue = printValue;
        }
        @Override
        public void run() {
            for(int i = 0;i<5;i++){
                if(flag){
                    System.out.println("1");
                }else{
                    System.out.println("2");
                }
                flag = !flag;
            }
        }
    }
} 

结果:

1
2
1
2
1
2
1
2
1
2

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: ``` class PrinterThread extends Thread { private String name; public PrinterThread(String name) { this.name = name; } public void run() { for (int i = 0; i < 10; i++) { System.out.println(name + ": " + i); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } } public class Main { public static void main(String[] args) { PrinterThread t1 = new PrinterThread("Thread 1"); PrinterThread t2 = new PrinterThread("Thread 2"); t1.start(); t2.start(); } } ``` 该代码创建了两个线程`PrinterThread t1`和`PrinterThread t2`,并在`run`方法中实现了循环打印。每个线程在每次循环打印后休眠100毫秒,以让另一个线程有机会执行。 ### 回答2: 可以使用Java的多线程机制来实现两个线循环打印的功能。以下是示例代码: ```java public class LoopPrinting { private static final Object lock = new Object(); private static int num = 1; private static int count = 1; public static void main(String[] args) { Thread threadA = new Thread(new PrintThread("A", 1)); Thread threadB = new Thread(new PrintThread("B", 2)); threadA.start(); threadB.start(); } static class PrintThread implements Runnable { private String threadName; private int threadNumber; public PrintThread(String threadName, int threadNumber) { this.threadName = threadName; this.threadNumber = threadNumber; } @Override public void run() { while (num <= 100) { synchronized (lock) { if (count % 3 == threadNumber - 1) { System.out.println(threadName + ":" + num); num++; count++; lock.notifyAll(); } else { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } } } ``` 在上述代码中,定义了一个共享的锁对象`lock`,一个共享的计数变量`num`和一个判断打印顺序的变量`count`。两个线程`ThreadA`和`ThreadB`通过`PrintThread`类实例化,并传入不同的线程名和线程编号。 在`PrintThread`的`run`方法中,使用`synchronized`关键字锁定`lock`对象,保证在每个线程执行时只有一个线程能够访问共享资源。通过判断`count`变量的值,实现两个线循环打印。其中`count % 3`的结果等于`threadNumber`减一,表示该线程可以进行打印操作。 当线打印完一个数字后,更新`num`和`count`的值,并使用`lock.notifyAll()`唤醒其他正在等待的线程。然后当前线程释放锁并进入等待状态,直到其他线程唤醒它。 ### 回答3: 可以使用Java中的多线程编程来实现两个线程的循环打印。以下是一个简单的示例代码: ```java public class TwoThreadPrinting { private static final Object lock = new Object(); private static volatile boolean isThread1Turn = true; // 标识线程1是否应该打印 public static void main(String[] args) { Thread thread1 = new Thread(new PrintThread(1)); Thread thread2 = new Thread(new PrintThread(2)); thread1.start(); thread2.start(); } private static class PrintThread implements Runnable { private final int threadNumber; public PrintThread(int threadNumber) { this.threadNumber = threadNumber; } @Override public void run() { try { for (int i = 1; i <= 10; i++) { synchronized (lock) { // 如果当前线程不是轮到自己打印,则当前线程等待 while ((threadNumber == 1 && !isThread1Turn) || (threadNumber == 2 && isThread1Turn)) { lock.wait(); } System.out.println("Thread " + threadNumber + ": " + i); isThread1Turn = !isThread1Turn; // 切换下一个线程的打印权限 lock.notifyAll(); // 唤醒所有等待的线程 } } } catch (InterruptedException e) { e.printStackTrace(); } } } } ``` 在上述代码中,我们定义了一个`TwoThreadPrinting`类,并在该类中创建了两个线程对象`thread1`和`thread2`。每个线程都被分配了一个`PrintThread`实例,其中`PrintThread`实现了`Runnable`接口,并且重写了`run`方法。在`run`方法中,通过`synchronized`关键字和`wait`、`notifyAll`方法来实现线程的同步与等待。 在程序运行过程中,每个线程都会进行循环打印10次,打印的内容格式为`Thread x: y`,其中`x`表示线程编号,`y`表示打印的数字。线程1在打印完当前数字后,会将`isThread1Turn`设置为`false`,然后唤醒线程2;而线程2在打印完当前数字后,会将`isThread1Turn`设置为`true`,然后唤醒线程1。这样两个线程就能够循环打印了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值