Java 多线程的一点小问题

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/guchuanhang/article/details/84646678

Java 多线程的一点小问题


使用了Runnable、Thread就必定是多线程?

    class XXRunnable implements java.lang.Runnable{
        @Override
        public void run() {
            Log.d(TAG,"runnable threadId"+ Thread.currentThread().getId());
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG,"main threadId"+ Thread.currentThread().getId());
        new Thread(new XXRunnable()).run();
    }

这个时候
11-30 11:46:49.449 10738-10738/? D/MainActivity: main threadId1
11-30 11:46:49.449 10738-10738/? D/MainActivity: runnable threadId1
有没有发现同一个线程ID呀!?
采用同一套测试框架


        new XXRunnable().run();  //和调用的线程同一个线程
        new Thread(new XXRunnable()).start(); //这才是多线程呢!?
展开阅读全文

Java的JDBC的一点小问题

05-21

public class ExecuteDDl rn private String driver;rn private String url;rn private String user;rn private String pass;rn rn public void initParam(String paramFile)throws Exceptionrn //使用Properties类来加载属性文件rn Properties props = new Properties();rn props.load(new FileInputStream(paramFile));rn driver = props.getProperty("com.mysql.cj.jdbc.Driver");rn url = props.getProperty("jdbc:mysql://localhost:3306/localhost");rn user = props.getProperty("root");rn pass = props.getProperty("asd857448959");rn rn public void createTable(String sql)throws Exceptionrn //加载驱动rn Class.forName(driver);rn try(rn //获取数据库链接rn Connection conn = DriverManager.getConnection("url", "user", "pass");rn //使用Connection来创建一个 Statement对象rn Statement stmt = conn.createStatement())rn rn //执行DDL语句,创建数据表rn stmt.executeUpdate(sql);rn rn rn rn public static void main(String[] args)throws Exceptionrn ExecuteDDl ed = new ExecuteDDl();rn ed.initParam("mysql.ini");rn ed.createTable("create table jdbc_test"rn +"( jdbc_id int auto_increment primary key,"rn +"jdbc_name varchar(255),"rn + "jdbc_desc text);");rn System.out.println("-----建表成功--------");rn rnrnrnrnrn当这代码执行产生一下错误rnException in thread "main" java.lang.NullPointerExceptionrn at java.base/java.lang.Class.forName0(Native Method)rn at java.base/java.lang.Class.forName(Unknown Source)rn at JDBCno1.ExecuteDDl.createTable(ExecuteDDl.java:26)rn at JDBCno1.ExecuteDDl.main(ExecuteDDl.java:41)rn麻烦各位小哥哥小姐姐了,这个弄了挺久就是不知道咋办~~~ 论坛

Java Swing 的一点小问题

02-21

rnimport java.awt.*;rnrnimport javax.swing.*;rnrnpublic class list rn public static void main(String args[]) rn // Container container = f.getContentPane();rn // 获得与JFrame关联的ContentPane,ContentPane的默认布局管理器是BorderLayout;rnrn // final Object rowData[][] = rn // "1", "one", "I" ,rn // "2", "two", "II" ,rn // "3", "three", "III" ;rn rn // final String columnNames[] = "姓名", "性别", "年龄","职务" ;rnrn final JTable Table = new JTable(20, 6);// 创建表格;rn Table.setRowHeight(25);// 设置表格的行高;rnrn JScrollPane scrollPane = new JScrollPane(Table);// 创建滚动条rnrn JFrame f = new JFrame("员工表");// 创建JFrame对象;rn f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// 点关闭,停止进程rnrn JPanel NorthPanel = new JPanel();rn // 创建北面的JPanel对象;rn JLabel label = new JLabel("员工信息表");rn Font font = new Font("宋体", 10, 20);// 新建字体;rn label.setFont(font);// 应用字体;rn NorthPanel.add(label);// 把标签添加到NorthPanel中;rnrn JPanel SouthPanel = new JPanel();rn rn Button button1 = new Button("增加");rn rn Button button2 = new Button("删除");rn Button button3 = new Button("查找");rn Button button4 = new Button("修改");rnrn SouthPanel.add(button1);rn SouthPanel.add(button2);rn SouthPanel.add(button3);rn SouthPanel.add(button4);rnrn f.add(SouthPanel, BorderLayout.SOUTH);rn f.add(NorthPanel, BorderLayout.NORTH);// 加入标签”员工信息表“;rn f.add(scrollPane, BorderLayout.CENTER);// 把NorthPanel添加到container中;rnrn // f.setResizable(false);//定义窗口是否可调整大小rn f.setSize(700, 550);// 定义JFrame窗口大小;rn f.setLocationRelativeTo(f);// 窗口居中显示;rn f.setVisible(true);// 显示窗口rn rnrnrn有两个问题:rn1、想让表格只占窗口的一半(窗口目前的大小不变),就是设置表格的大小!rn2、设置Button的大小,我用setSize方法设置不管用啊!rnrn高手来帮帮忙!多谢啦! 论坛

java http 的一点小问题

04-27

首先写了一个servletrn[code=java]package com.zf.login;rnrnimport java.io.IOException;rnimport java.io.PrintWriter;rnrnimport javax.servlet.ServletException;rnimport javax.servlet.http.HttpServlet;rnimport javax.servlet.http.HttpServletRequest;rnimport javax.servlet.http.HttpServletResponse;rnrnpublic class LoginServlet extends HttpServlet rnrn /**rn * Constructor of the object.rn */rn public LoginServlet() rn super();rn rnrn /**rn * Destruction of the servlet. rn */rn public void destroy() rn super.destroy(); // Just puts "destroy" string in logrn // Put your code herern rnrn /**rn * The doGet method of the servlet. rn *rn * This method is called when a form has its tag value method equals to get.rn * rn * @param request the request send by the client to the serverrn * @param response the response send by the server to the clientrn * @throws ServletException if an error occurredrn * @throws IOException if an error occurredrn */rn public void doGet(HttpServletRequest request, HttpServletResponse response)rn throws ServletException, IOException rn rn String username = request.getParameter("username"); //得到usernamern String password = request.getParameter("password"); //得到passwordrn System.out.println("username = "+username);rn System.out.println("password = "+password);rn response.setContentType("text/html");rn response.setContentType("utf-8");rn PrintWriter out = response.getWriter();rn /*rn outrn .println("");rn out.println("");rn out.println(" A Servlet");rn out.println(" ");rn out.print(" This is ");rn out.print(this.getClass());rn out.println(", using the GET method");rn out.println(" ");rn out.println("");rn out.flush();rn out.close();rn */rn rnrn /**rn * The doPost method of the servlet. rn *rn * This method is called when a form has its tag value method equals to post.rn * rn * @param request the request send by the client to the serverrn * @param response the response send by the server to the clientrn * @throws ServletException if an error occurredrn * @throws IOException if an error occurredrn */rn public void doPost(HttpServletRequest request, HttpServletResponse response)rn throws ServletException, IOException rnrn String username = request.getParameter("username"); //得到usernamern String password = request.getParameter("password"); //得到passwordrn System.out.println("username = "+username);rn System.out.println("password = "+password);rn response.setContentType("text/html");rn response.setContentType("utf-8");rn PrintWriter out = response.getWriter();rn rn /*rn outrn .println("");rn out.println("");rn out.println(" A Servlet");rn out.println(" ");rn out.print(" This is ");rn out.print(this.getClass());rn out.println(", using the POST method");rn out.println(" ");rn out.println("");rn out.flush();rn out.close();rn */rn rnrn /**rn * Initialization of the servlet. rn *rn * @throws ServletException if an error occursrn */rn public void init() throws ServletException rn // Put your code herern rnrnrn[/code]rnrn然后协议一个测试http的代码:rn[code=java]import javax.net.ssl.HttpsURLConnection;rnimport java.net.URL;rnimport java.io.InputStream;rnpublic class TestHttp rnrn public static void main(String[] args) rn rn rn tryrn new Thread()rn String startUrl="http://192.168.1.106:8080/loginTest/servlet/LoginServlet?username=ddd&password=dddd"; //记录路径rn URL url = new URL(startUrl);rn HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();rn .start();rn rn catch(Exception e)rn e.printStackTrace();rn System.out.println("连接失败啊!!!");rn rn rnrn[/code]rnrn我直接在浏览器进入的时候servlet端会有东西打印出来,而运行测试的时候显示连不上是怎么回事啊? 论坛

java多线程问题的求救

09-28

rnpublic class textThread rnrn public static void main(String args[])rn Runner1 r =new Runner1(); rn r.run();rn //Thread t=new Thread(r);rn //t.start();rnrn rn for(double i=0;i<10000;i++)rn System.out.println("main thread..."+i);rn rn rn rn rnrn rn rnrn rn class Runner1 implements Runnablern public void run()rn for(double i=0;i<10000;i++)rn System.out.println("Runnable1..."+i);rn rn rn rnrnrn////////////////////////////////请问大家 输出结果为什么不是由一开始的?如果我把10000改为100就输出正常了rn当前程序输出结果是:main thread...6232.0 rnmain thread...6233.0rnmain thread...6234.0rnmain thread...6235.0rnmain thread...6236.0rnmain thread...6237.0rnmain thread...6238.0rnmain thread...6239.0rnmain thread...6240.0rnmain thread...6241.0rnmain thread...6242.0rnmain thread...6243.0rnmain thread...6244.0rnmain thread...6245.0rnmain thread...6246.0rnmain thread...6247.0rnmain thread...6248.0rnmain thread...6249.0rnmain thread...6250.0rnmain thread...6251.0rnmain thread...6252.0rnmain thread...6253.0rnmain thread...6254.0rnmain thread...6255.0rnmain thread...6256.0rnmain thread...6257.0rnmain thread...6258.0rnmain thread...6259.0rnmain thread...6260.0rnmain thread...6261.0rnmain thread...6262.0rnmain thread...6263.0rnmain thread...6264.0rnmain thread...6265.0rnmain thread...6266.0rnmain thread...6267.0rnmain thread...6268.0rnmain thread...6269.0rnmain thread...6270.0rnmain thread...6271.0rnmain thread...6272.0rnmain thread...6273.0rnmain thread...6274.0rnmain thread...6275.0rnmain thread...6276.0rnmain thread...6277.0rnmain thread...6278.0rnmain thread...6279.0rnmain thread...6280.0rnmain thread...6281.0rnmain thread...6282.0rnmain thread...6283.0rnmain thread...6284.0rnmain thread...6285.0rn............................下面不写了 论坛

java多线程的一点思考

06-19

笔者是一个普通大学大二非计算机专业的学生,在学习java多线程问题的时候出于某种原因碰见了一个难以解决的问题。之所以说是难以解决,是因为它既不是逻辑问题,也不是语法问题。笔者对java的认识并不深刻,特此将这个问题拿上来同各路大牛分享,希望能得到一个满意的答复,先谢过各路大牛~rn 笔者有长时间在贴吧潜水的经历,懂得提问的规矩,为了帮助大家理解我遇到的问题,我特地写了测试程序(如下),并把我的一些挣扎和思考的过程意义列举出来。rnrn测试程序如下:rn运行环境:JDK1.6rnrn[code=java]rnpackage TestThread;rnrnpublic class TestThread rn //定义Flag,Flag = true,分线程空转,Flag = false,分线程执行输出rn private static boolean Flag = false; rn rn //分线程rn class MyThread implements Runnablern @Overridern public void run()rn while(true)rn System.out.println("分线程debug语句");rn while(!Flag)rn for(int i = 0;i < 200;i++)rn System.out.println("分线程输出");rn rn rn rn rn rn rn //主线程rn public static void main(String[] args)rn TestThread tt = new TestThread();rn rn //启动分线程rn MyThread mt = tt.new MyThread();rn Thread t = new Thread(mt);rn t.start();rn rn //主线程sleep3srn System.out.println("让分线程输出3s");rn try rn Thread.sleep(3000);rn catch (InterruptedException e) rn e.printStackTrace();rn rn rn System.out.println("让分线程空转3s");rn Flag = true;rn rn //主线程sleep3srn try rn Thread.sleep(3000);rn catch (InterruptedException e) rn e.printStackTrace();rn rn rn System.out.println("让分线程输出");rn Flag = false; rn System.out.println(t.isAlive());rn rn rnrn[/code]rnrnrnrn测试程序描述的是两个线程并发的过程,思路比较明确,不多赘述。笔者通过主线程给分线程传递不同的信号量(Flag = true or false),使分线程在Flag = true时什么也不做,输出debug语句,在Flag = false时,输出内层while循环的语句。rn主线程执行如下功能:1、激活分线程,Flag = false;2、三秒之后,Flag = true;3、三秒之后,Flag = false。得到的运行结果和预期一样:分线程先输出内层循环语句,三秒空转,然后再输出内层循环语句。rnrnrn然后问题来了。笔者手贱,将System.out.println("分线程debug语句");一行给注释掉了。rnrn代码如下:rn[code=java]rnpackage TestThread;rnrnpublic class TestThread rn //定义Flag,Flag = true,分线程空转,Flag = false,分线程执行输出rn private static boolean Flag = false; rn rn //分线程rn class MyThread implements Runnablern @Overridern public void run()rn while(true)rn //System.out.println("分线程debug语句");rn while(!Flag)rn for(int i = 0;i < 200;i++)rn System.out.println("分线程输出");rn rn rn rn rn rn rn //主线程rn public static void main(String[] args)rn TestThread tt = new TestThread();rn rn //启动分线程rn MyThread mt = tt.new MyThread();rn Thread t = new Thread(mt);rn t.start();rn rn //主线程sleep3srn System.out.println("让分线程输出3s");rn try rn Thread.sleep(3000);rn catch (InterruptedException e) rn e.printStackTrace();rn rn rn System.out.println("让分线程空转3s");rn Flag = true;rn rn //主线程sleep3srn try rn Thread.sleep(3000);rn catch (InterruptedException e) rn e.printStackTrace();rn rn rn System.out.println("让分线程输出");rn Flag = false; rn System.out.println(t.isAlive());rn rn rnrn[/code]rnrnrn然后笔者得到的执行结果是:三秒分线程先输出内层循环语句,三秒空转,然后再输出内层循环语句。当主线程再将Flag = false时,分线程却没有如期地再次输出内层循环(笔者亲验)。rnrn笔者不相信自己的眼睛,于是调用了isAlive函数去看看分线程是否还活着,结果返回true,分线程确实还存在,但是却不工作了。笔者才疏学浅,无法解释这一现象,但是在和伙伴的交流讨论中,得出了如下两种推论。这两种可能有一种是正确的,也有可能都是错的,现在都列出来,请各路大牛批评指正:rn1、分线程内循环在某个时刻接受到true(不工作)时,java虚拟机认为该线程做的是无用功,虽然分线程还活着,但是不再为其分配CPU,即使是分线程后来又可以正常工作了。rn2、分线程内循环在某个时刻接受到true(不工作)时,java虚拟机认为该线程做的是无用功,自己给代码做了优化,莫名其妙就变成这个样子了。rnrn第二种观点是我的小伙伴提出来的。刚开始提出来的时候我认为他说的跟我第一种的想法其实是一个意思,他说不一样。他认为我的想法(第一种)是在运行时发生的,而他的想法是代码在编译阶段已经产生了分歧,即两段代码虽然只是一句System.out之差,编译的结果却是大不相同的。为了说服我,他(大牛)给我导出了两段代码各自的字节码作比较。然而我并不能看懂……我也不知道如何导出字节码,所以字节码就不上代码了,感兴趣的大牛辛苦一下哈,可以自己试试导出看看……rnrn以上就是我遇到的问题。这是笔者提问的处女贴,希望各路大牛不吝赐教,在此先谢过了! 论坛

java 卡片布局管理器的一点小问题

09-08

[code=Java]rnrnimport java.awt.*;rnimport java.awt.event.*;rnpublic class CardLayoutDemo extends Frame implements MouseListenerrnrn private Button first=new Button("A");rn private Button second=new Button("B");rn private Button third=new Button("C");rn private CardLayout cl=new CardLayout();rn private Panel cards=new Panel();rnrn public CardLayoutDemo(String string)rn super(string);rn init(); //调用init方法rn rn rn public void init()rn setLayout(new BorderLayout());rn setSize(500, 500);rn rn Panel p=new Panel();rn p.setLayout(new FlowLayout());rn rn first.addMouseListener(this);rn second.addMouseListener(this);rn third.addMouseListener(this);rn rn p.add(first);rn p.add(second);rn p.add(third);rn rn add("North",p);rn cards.setLayout(cl);rn cards.add("First cards",new Button("AA"));rn cards.add("second Button",new Button("BB"));rn cards.add("third cards",new Button("CC"));rn add("Center",cards);rn rn addWindowListener(new WindowAdapter()rn public void WindowClosing(WindowEvent evt)rn setVisible(false);rn dispose();rn System.exit(0);rn rn );rn rn setVisible(true);rn rn rn public static void main(String[] args) rn new CardLayoutDemo("ABCD"); //创建CardLayoutDemo类型变量 rn rn rn rnpublic void mouseClicked(MouseEvent evt)rn if(evt.getSource()==first)rn cl.first(cards);rnrnelse if(evt.getSource()==second)rn cl.first(cards);rn cl.next(cards);rnrnelse if(evt.getSource()==third)rn cl.last(cards);rnrnrn public void mouseEntered(MouseEvent arg0)rn rn public void mouseExited(MouseEvent arg0)rn rn public void mousePressed(MouseEvent arg0)rn rn public void mouseReleased(MouseEvent arg0)rn rn rnrnrnrnrn[/code]rnrn有些地方一直搞不懂,请老手教下新手rnrn1.前面学了其他的布局管理器。 都没看到 实例化布局管理器。这里有private CardLayout cl=new CardLayout(); 为什么要对布局器实例化对象呢?有什么用意吗?rnrn2.init方法中 设置窗口布局和大小的时候 不需要先对Frame窗口实例化再调用吗? 为什么可以直接这样写?rnrn3.在main中 为什么不需要设置对象啊?rnrn4.为什么要在构造方法中调用init方法啊?rnrn5.在cards中添加按钮 为什么需要些"first Button" 。为什么要写这个?能不写或随便写吗? 论坛

没有更多推荐了,返回首页