基本使用
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);
}
}