一
* 第一种创建线程的方式
* 继承Thread类,重写run方法
public class ThreadDemo3 {
public static void main(String[] args){
//1
Thread t1 = new Thread(){
public void run(){
for(int i=0;i<1000;i++){
System.out.println("你是谁啊");
}
}
};
//2
Runnable runn = new Runnable(){
public void run(){
for(int i=0;i<1000;i++){
System.out.println("我是查水表的");
}
}
};
Thread t2 = new Thread(runn);
t1.start();
t2.start();
}
}
* 第二种创建线程的方式
* 定义线程体Runnable
public class ThreadDemo2 {
public static void main(String []args){
Runnable runn1 = new MyRunnable1();
Runnable runn2 = new MyRunnable2();
Thread t1 = new Thread(runn1);
Thread t2 = new Thread(runn2);
t1.start();
t2.start();
}
}
class MyRunnable1 implements Runnable{
public void run(){
for(int i=0;i<1000;i++){
System.out.println("你是谁啊");
}
}
}
class MyRunnable2 implements Runnable{
public void run(){
for(int i=0;i<1000;i++){
System.out.println("我是修水管的");
}
}
}
三
常用API
四
线程同步
五
线程协同工作
synchronized关键字
六
线程协同工作例子
比如我们有两个线程,一个是下载图片的线程,一个是显示图片的线程
显示图片的线程必须等待下载图片的线程运行完成后才能运行
public class ThreadDemo10 {
public static boolean isFinish;
public static Object obj = new Object();
public static void main(String[] args){
//下载线程
final Thread download = new Thread(){
public void run(){
System.out.println("down:开始下载图片..");
for(int i=1;i<=100;i++){
System.out.println(
"down:已完成"+i+"%");
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
}
System.out.println("down:图片下载完毕");
isFinish = true;
/*
* 当图片下载完毕,就应当通知显示图片的
* 线程开始工作了
*/
synchronized(obj){
obj.notify();
}
System.out.println("down:开始下载附件..");
for(int i=1;i<=100;i++){
System.out.println(
"down:已完成"+i+"%");
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
}
System.out.println("down:附件下载完毕");
}
};
Thread show = new Thread(){
public void run(){
System.out.println("show:开始显示图片..");
//这里应当等待下载线程将图片下载完毕
try {
// download.join();
//在obj对象上等待
synchronized(obj){
obj.wait();
}
} catch (InterruptedException e) {
}
if(!isFinish){
throw new RuntimeException(
"图片没有找到");
}
System.out.println(
"show:显示图片完毕..");
}
};
download.start();
show.start();
}
}
七
线程池
ExecutorService关键字
/**
* 线程池
* 用于重用线程以及控制线程数量
*
*
*/
public class ThreadPoolDemo {
public static void main(String[] args){
ExecutorService threadPool
= Executors
.newFixedThreadPool(2);
for(int i=0;i<5;i++){
Runnable runn
= new Runnable(){
public void run(){
for(int i=0;i<5;i++){
System.out.println(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
threadPool.execute(runn);
}
}
}