java thread 创建_java多线程创建方式一Thread

基本使用

package com.sgg.thread;

/**

* 多线程的创建。方式1继承与Thread类

* 1.创建一个继承与Thread的子类

* 2.重写run方法,将此线程执行的操作声明在run方法中

* 3.创建Thread子类对象

* 4.通过此对象调用start()方法启动线程

*

*/

public class TestThread {

public static void main(String[] args) {

//ConcurrentHashMap objectObjectConcurrentHashMap = new ConcurrentHashMap();

MyThread myThread = new MyThread();

myThread.start();

//使用匿名方式继承

//        new Thread(){

//

//            @Override

//            public void run() {

//                for (int i = 0; i < 100; i++) {

//                    if (i%2 == 1 ){

//                        System.out.println(Thread.currentThread().getName()+":"+i);

//                    }

//

//                    if(i%20 == 0){

//                        //释放CPU的执行权

//                        this.yield();

//                    }

//

//                }

//            }

//        }.start();

for (int i = 0; i < 100; i++) {

if (i%2 == 1 ){

System.out.println(Thread.currentThread().getName()+":"+Thread.currentThread().getPriority()+":"+i);

}

if( i== 10){

try {

myThread.join();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

System.out.println("myThread是否存活:"+myThread.isAlive());

}

}

//使用集成方式

class MyThread extends Thread{

@Override

public void run() {

for (int i = 0; i < 100; i++) {

if (i%2 ==0 ){

try {

sleep(1000);

} catch (InterruptedException e) {

e.printStackTrace();

}

System.out.println(Thread.currentThread().getName()+":"+i);

}

}

}

public MyThread(){};

//创建时设置线程名字

public MyThread(String name){

//调用java.lang.Thread.Thread(java.lang.String)

super(name);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值