第三天,Java基础学习_线程

来源:互联网 发布:赌nba的软件 编辑:程序博客网 时间:2024/06/13 00:57

1.       异常处理try{}cath{system.out.println(“出错啦!”)}

2.       数组,mainstring[] argsargs收纳从命令行输入的字符串们。
system.arraycopy
(【从】原数组.起始位,【到】新数组.起始位,【拷贝位数】位数【原数组.Length】)

3.     线程的格式package com.panpan;
public class testRunner {
public static void main(String[] args) {
// 1
。用implements创建类//给类创建线程//启动线程【a1.run不是线程,而是方法调用】
    Runner1 a1= new Runner1();Thread  a11= new Thread(a1); a11.start();
//2.
extends创建类//启动线程
    Runner2 a2= new Runner2();a2.start();
//
主函数的东西们,
    for(int i= 0;i<100;i++){   System.out.println("主程序在运行...."+i);    }}}
//推荐使用接口,不使用继承
class Runner1 implements Runnable {//推荐使用接口,不使用继承
    //run
runnable里的抽象类在子类里必须实现或者重写
    public void run(){for(int i= 0;i<100;i++){System.out.println("Runner1
在运行.."+i);}}}
class Runner2 extends Thread {
    //run
runnable里的抽象类在子类里必须实现或者重写}
    public void run(){for(int i= 0;i<200;i++){System.out.println("Runner2
在运行.."+i);}}}

4.sleep【如何用接口方式实现】
        try{Thread.sleep(10000);}       catch (InterruptedException e){ }
        a1.interrupt(); //
线程睡眠10秒,然后执行

        try{    sleep(20000);} catch(InterruptedException e){return;  }//线程睡眠20秒,期间出现异常,线程返回或者结束

5.join【线程合并】public static void main(String[] args) {
        tj a1= new tj("testjoin");a1.start();   //
线程已经运行,,,
        try{Thread.sleep(3000);}    catch(InterruptedException e){}//
线程已经运行,

        System.out.println("下面是");  
       
try{ a1.join(); }//线程被插入到主线程下接着上次运行
        catch(InterruptedException e){ }
        for(int i= 0;i<10;i++){System.out.println("
主函数");    }

6.synchronized (this){sleep(100)}【线程同步】,//如果某个线程调用这个代码,则其他线程就得等待这段代码执行完后才能调用,即使这个代码间被睡眠了,也不能被其他线程调用。  【线程互锁,,解决1。可以把锁的范围扩大】
public class testclook implements Runnable{ int a= 1;

public void run(){try{qq();} catch (Exception e){ }  }

public synchronized void qq() throws Exception{a=9; Thread.sleep(5000);     System.out.println("qq"+a); }
public void ww(){a=5;System.out.println("ww"+a);   }
public static void main(String[] args)  throws Exception {   testclook a1= new testclook();Thread a2= new Thread(a1);a2.start();//
线程“qq”被锁

Thread.sleep(1000); //线程“qq”依然被锁 如果去掉“Thread.sleep(1000);”则“ a1.ww();”会比线程“qq先启动”

a1.ww();//主线程“a1可以修改“qq”线程里的数据但是不能调用被锁住的代码}}

【有关于线程同步和互锁之间的关系,,有待加深。。。有点多、视频毕竟只是一点儿。】