会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132837个问题

老师,为啥运行了几次之后会出现先消费馒头啊/** * 消费者与生产者 */package com.company;/** * 定义一个馒头类 */class ManTou{ private int Id; public ManTou(int Id){ this.Id=Id; } public int getId() { return Id; }}/** * 定义缓冲区 */class SyncStack{ //定义存放盒子的馒头 private ManTou[] mt =new ManTou[10]; //定义操作盒子的索引 private int index; /** * 放馒头 */ public synchronized void push(ManTou manTou){ //判断盒子是否已满 while (this.index==this.mt.length) try { /** * 语法:wait();该方法必须要在synchronized块中调用。 * wait();执行后,会将持有的对象锁释放,并进入阻塞状态。 * 其他需要该对象锁的线程就可以继续运行了。 */ this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } //唤醒取馒头的线程 /** * 语法:必须要在synchronized块中调用。 * 该方法会唤醒等待状态队列中的一个线程。 */ this.notify(); this.mt[this.index]=manTou; this.index++; } /** * 取馒头 * @return */ public synchronized ManTou pop(){ while (this.index==0){ try { /** * 语法:wait();该方法必须要在synchronized块中调用。 * wait();执行后,会将持有的对象锁释放,并进入阻塞状态。 * 其他需要该对象锁的线程就可以继续运行了。 */ this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } /** * 语法:必须要在synchronized块中调用。 * 该方法会唤醒等待状态队列中的一个线程。 */ this.notify(); this.index--; return this.mt[this.index]; }}/** * 生产者线程 */class Shengchan extends Thread{ private SyncStack ss; public Shengchan(SyncStack ss){ this.ss=ss; } @Override public void run() { for (int i=0;i<10;i++){ System.out.println("生产馒头:"+i); ManTou manTou=new ManTou(i); this.ss.push(manTou); } }}/** * 消费者线程 */class xiaofei extends Thread{ private SyncStack ss; public xiaofei(SyncStack ss){ this.ss=ss; } @Override public void run() { for (int i=0;i<10;i++){ System.out.println("消费馒头:"+i); } }}public class ProduceThread { public static void main(String[] args) { SyncStack ss=new SyncStack(); new Shengchan(ss).start(); new xiaofei(ss).start(); }}

JAVA 全系列/第二阶段:JAVA 基础深化和提高/多线程技术(旧) 1351楼
JAVA 全系列/第二阶段:JAVA 基础深化和提高/网络编程(旧) 1357楼

package com.bjsxt.socket;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * 发送信息线程
 */
class ClientSend extends Thread{
    private Socket socket;
    ClientSend(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        this.sendMsg();
    }
    /**
     * 发送消息
     */
    private void sendMsg(){
        Scanner scanner = null;
        PrintWriter pw = null;
        try {
            scanner  = new Scanner(System.in);
            pw = new PrintWriter(this.socket.getOutputStream());
            String str = scanner.nextLine();
            while (true){
                if ("exit".equals(str)){
                    break;
                }
                pw.println(str);
                pw.flush();
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (pw!=null){
                pw.close();
            }
            if (scanner!=null){
                scanner.close();
            }
        }

    }
}
/**
 * 接受消息线程
 */
class ClientReceive extends Thread{
    private Socket socket;
    ClientReceive(Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        this.receiveMsg();
    }
    /**
     * 接受消息
     */
    private void receiveMsg(){
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            while (true){
                String clientStr = br.readLine();
                if ("exit".equals(clientStr)){
                    break;
                }
                System.out.println("客户端说:"+clientStr);
            }


        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
public class ChatSocketClient {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("127.0.0.1",8888);
            System.out.println("连接成功!");
            new ClientReceive(socket).start();
            new ClientSend(socket).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

image.png

老师,为啥我这里死循环了,大家都用的where(true)了呀,而且我前面的双向通信和单向都用的了where(true)

和老师写的差不多,到点对点练习就死循环了

JAVA 全系列/第二阶段:JAVA 基础深化和提高/网络编程(旧) 1363楼

老师,使用 new 关键字新建 Student 类的对象 student,和获取 Class 对象,然后调用 newInstance() 方法新建对象 students 有啥区别?应该都算是调用 Student 类的无参构造器新建对象吧。

public class ReflectionPerformanceTest01 {

    public static void main(String[] args) throws Exception {
        // Reflection
        // obtain Class object
        Student student = new Student();
        Class classObject01 = student.getClass();

        Class classObject02 = Student.class;

        Class classObject03 = Class.forName("com.bjsxt.demo.Student");

        // test students is equal student?是不是都是算是调用无参构造器创建对象?
        // 此外,使用这两种方式创建的对象调用方法,很明显一个使用了反射,一个没有使用反射,所以效率会有明显的差距。
        Student students =(Student) classObject03.newInstance();

        long reflectionStart = System.currentTimeMillis();
        Method method = classObject03.getMethod("setName", String.class);

        final int cycle = 10000000;
        for ( int i = 0; i < cycle; ++i) {
            // method.invoke(student,"John");   // new 关键字新建对象 student
            method.invoke(students,"John");   // Class 对象调用 newInstance() 方法获取对象
        }
        long reflectionEnd = System.currentTimeMillis();
        System.out.println(reflectionEnd - reflectionStart);
        System.out.println("----------------");

        // non reflection
        long start = System.currentTimeMillis();
        for (int i = 0; i < cycle; ++i) {
            student.setName("Marry");
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }
}


JAVA 全系列/第二阶段:JAVA 基础深化和提高/反射技术(旧) 1364楼

User 类:

public class User {

    private String userName;
    private int userAge;
    public String location;

    public User() {
    }

    public User(String userName, int userAge, String location) {
        this.userName = userName;
        this.userAge = userAge;
        this.location = location;
    }

    // private modifier
    private User(int userAge) {
        this.userAge = userAge;
    }

     /*only the name is different, can not constitute an overload,
     so it can not add the constructor that only have a location parameter.*/
    public  User(String userName) {
        this.userName = userName;
    }

    public User(String userName, String location) {
        this.userName = userName;
        this.location = location;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public int getUserAge() {
        return userAge;
    }

    public void setUserAge(int userAge) {
        this.userAge = userAge;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public void testMethod () {
        System.out.println("hello!");
    }

    private void testWay () {
        System.out.println("overload");
    }

    public void testWay (int id) {
        System.out.println(id);
    }

    @Override
    public String toString() {
        /* Considering code writing from the bottom level, in order to cope with different functional requirements */
        return "User{" +
                "userName='" + this.getUserName()+ '\'' +
                ", userAge=" + this.getUserAge()+
                ", location='" + this.getLocation() + '\'' +
                '}';
    }
}

通过反射调用方法测试类:

public class GetMethodTest02 {

    public static void main(String[] args) {
        User user01 = new User();
        Class classObject01 = user01.getClass();

        Class classObject02 = User.class;

        Class classObject03 = null;
        try {
            classObject03 = Class.forName("com.bjsxt.demo.User");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        /* call the public method */
        Method method01 = null;
        try {
            method01 = classObject03.getDeclaredMethod("testWay",int.class);   // get designed method object.
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        Object user02 = null;
        try {
            user02 = classObject03.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        try {
            method01.invoke(user02,3);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        // how call the private method?

    }
}

老师,在调用方法的测试类中,如何调用自定义的用 private 修饰的 testWay() 方法?还是说通过反射只能调用类的 public 方法,不能调用 pirvate 的方法.

JAVA 全系列/第二阶段:JAVA 基础深化和提高/反射技术(旧) 1365楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637