java多线程(一):线程的建立及简单操作

来源:互联网 发布:开放式网络 编辑:程序博客网 时间:2024/05/14 10:39
public class Java多线程 {    public static void main(String[] args) throws InterruptedException {        Mythread1 th1=new Mythread1();        th1.start();        System.out.println("线程1是否是活的:"+th1.isAlive());        th1.join();//等待th1执行完再执行后边的,可设置需要等待的毫秒数        System.out.println("线程1是否是活的:"+th1.isAlive());        MyRunnbale runnable=new MyRunnbale();        Thread th2=new Thread(runnable);        th2.start();        System.out.println("ID:"+th2.getId()+"  Name:"+th2.getName());//打印线程的ID和默认名字        th2.setName("Thread2");//设置线程的名字        System.out.println(th2.getName());//打印线程的名字    }}class Mythread1 extends Thread {//继承Thread类建立线程    public void run(){        System.out.println("线程1运行");        try {            mySleep();        } catch (InterruptedException e) {            e.printStackTrace();        }    }    void mySleep() throws InterruptedException{    for(int i=1;i<4;i++){        sleep(1000);        System.out.println("线程1休眠 "+i+" ms");        }    }}class MyRunnbale implements Runnable{//实现Runnable接口建立线程,是真正的可实现多线程(一般用这个)    public void run() {        System.out.println("线程2运行");    }}

输出:
这里写图片描述

0 0
原创粉丝点击