关键字 Thread runnable currentThread run start sleep yeid
线程的生命周期
1.新建线程
2.线程启动
3.线程运行
4.线程阻塞,
5.线程结束
一、线程的创建
1.第一种继承:
package com.yhw.demo;
/**
* 一.线程的概述
* 进程:运行的任务通常对应一个 进程;
* 程序运行的时候对应至少一个进程而 进程至少包含一个线程
* 多线程的优势
*
* 进程之间不能共享内存,但是线程之间可以共享内存
* 系统创建进程的时候要重新分配系统资源。但是线程创建的代价小得多,因此使用多线程来实现多任务并发比多进程的效率高
*
*二.线程的创建和启动
* java中 thread类代表线程
*
* 1.定义thread类的子类来创建线程,要重写run() 方法 线程中完成的任务也是在run方法体中进行
* 2.创建thread子类的事例,即创建了线程对象
* 3.调用线程的start() 方法启动线程
*
* @methon Thread.currentThread(); 获取当前线程
* Thread.currentThread().getName(); 获取当前线程名称
*
* @author Administrator
*
*/
public class ThreadDemo1 extends Thread{
public void run(){
for (int i = 0; i < 100; i++) {
System.out.println(this.getName());
}
}
public static void main(String[] args) {
//new ThreadDemo1().start();
System.out.println(Thread.currentThread().getName());
for (int i = 0; i < 100; i++) {
if(i==20){
Thread threadDemo1 = new ThreadDemo1();
threadDemo1.start();
Thread threadDemo2 = new ThreadDemo1();
threadDemo2.start();
}
}
}
}
2.种 Runnable 实现类实现
package com.yhw.demo;
class CreateRunnable implements Runnable{
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName()+"--"+i);
}
}
}
/**
*
* @author Administrator
*
*/
public class RunnableDemo {
public static void main(String[] args) {
new Thread(new CreateRunnable(),"Thread-01").start();
new Thread(new CreateRunnable(),"Thread-02").start();
}
}
3.匿名函数方式
package com.infree.thread;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import javax.swing.plaf.ListUI;
import com.infree.entity.UserEntity;
import com.infree.util.ListUtils;
/**
*
* @author Administrator
*
*/
public class BatchMain {
private static Scanner scanner;
public static void main(String[] args) {
int pageSize = 5;
List <List<UserEntity>> splitUserList= ListUtils.splitList(UserList(), pageSize);
int threadNum = splitUserList.size();
for (int i = 0; i < threadNum; i++) {
List<UserEntity> listUser = splitUserList.get(i);
new Thread(new Runnable(){
@Override
public void run() {
try {
for(UserEntity user: listUser){
System.out.println(Thread.currentThread().getName()+"============"+user);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
public static List<UserEntity> UserList () {
List<UserEntity> lists= new ArrayList<UserEntity>();
scanner = new Scanner(System.in);
int sum = 55;
System.out.println("sum"+sum);
for (int i = 0; i < sum; i++) {
lists.add(new UserEntity("userId--"+i, "userName--"+i));
}
return lists;
}
}