package com.xiaoming.homework04; /** * @ClassNameTest05 * @Description TODO * @Author 守护者 * @Date 2022/4/22 6:36 * @Version 1.0 **/ public class Test05 { public static void main(String[] args) { //这里创建一个对象用来配合synchronized来使用 Object o = new Object(); NumThread numThread = new NumThread(o); CharThread charThread = new CharThread(o); //开启线程 numThread.start(); charThread.start(); } } class NumThread extends Thread { private Object obj; public NumThread(Object obj) { this.obj = obj; } @Override public void run() { //同步代码块 synchronized (obj) { for (int i = 1; i <= 52; i++) { System.out.println(i); obj.notifyAll(); if (i % 2 == 0) { try { obj.wait(); } catch (InterruptedException e)
Thread线程问题
最新推荐文章于 2022-09-26 15:54:51 发布
该博客探讨了一个Java线程问题,通过`NumThread`和`CharThread`两个类展示了如何使用`synchronized`关键字进行线程同步。在`main`方法中创建了对象`o`作为锁,`NumThread`负责打印1到52的数字,而`CharThread`负责打印'a'到'z'的字符。两个线程在执行过程中交替唤醒和等待,当`NumThread`遇到偶数时,`CharThread`开始执行,反之亦然。博客内容详细说明了线程间的协作与通信机制。
摘要由CSDN通过智能技术生成