1.线程
进程:一个程序的执行
线程:程序中单个顺序的流控制,分享CPU,共享内存
线程体:
run()方法来实现
2.创建线程
(1)继承Thread类
public class Test{
public static void main(String[] args)
{
Thread t = new MyThread(10);
t.start();
}
}
class MyThread extends Thread
{
private int n;
public MyThread(int n)
{
super();
this.n = n;
}
public void run()
{
for(int i=0;i<n;i++)
{
System.out.println(" " + i);
}
}
}
(2)向Thread()构造方法传递Runnable对象来创建线程
public class Test{
public static void main(String[] args)
{
MyTask myTask = new MyTask(10);
Thread t = new Thread(myTask);
t.start();
for(int i=0; i<6; i++) {
System.out.println("Main--" + i);
try{
t.sleep(500);
}catch( InterruptedException e ){}
}
}
}
class MyTask implements Runnable
{
private int n;
public MyTask(int n)
{
this.n = n;
}
public void run()
{
for(int i=0;i<n;i++)
{
System.out.println(" " + i);
}
try
{
Thread.sleep(500);
}catch( InterruptedException e ){}
}
}
(3)匿名类或Lambda表达式
public class Test()
{
public static void main(String[] args)
{
new Thread(){
public void run()
{
for(int i=0; i<10; i++)
System.out.println(i);
}
}.start();
new Thread( ()->{
for(int i=0; i<10; i++)
System.out.println(i);
} ).start();
}
}
多线程例子1:
public class Test
{
public static void main(String[] args)
{
Counter c1 = new Counter(1);
Thread t1 = new Thread(c1);
Thread t2 = new Thread(c1);
Counter c2 = new Counter(10);
Thread t3 = new Thread(c2);
Thread t4 = new Thread(c2);
TimeDisplay timer = new TimeDisplayer;
Thread t5 = new Thread(timer);
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
class Counter implements Runnable
{
int id;
Counter(int id)
{
this.id = id;
}
public void run()
{
int i = 0;
while(i++<=10)
{
System.out.println("ID: " + id + " No." + i);
try
{Thread.sleep(10);} catch(InterruptedException e){}
}
}
}
class TimeDisplay implements Runnable
{
public void run()
{
int i = 0;
while(i++<=3)
{
System.out.println(new SimpleDateFormat().format(new Date()));
try
{Thread.sleep(40);} catch(InterruptedException e){}
}
}
}
例:多线程下载
import java.io.*;
import java.net.URL;
public Class Test{
public static void main(String[] args)
throws IOException
{
final URL[] urls = {
new URL("http://www.pku.edu.cn"),
new URL("http://www.baidu.com")
};
final String[] files = {
"pku.htm",
"baidu.htm"
};
for(int i = 0;i<urls.length;i++)
{
final int idx = i;
new Thread( ()->{
try{
System.out.println(urls[idx]);
download(urls[idx],files[idx]);
}catch(Exception ex){
ex.printStackTrace();
}
}).start();
}
}
static void download(URL url, String file)
throws IOException
{
try(InputStream input = url.openStream();
OutputStream output = new FileOutputStream(file))
{
byte[] data = new byte[1024];
int length;
while((length=input.read(data))!=-1)
{
output.write(data,0,length);
}
}
}
}
3.线程的控制
(a)基本控制
启动:start()
结束:标记变量
暂时阻止执行:
try{Thread.sleep(1000);} catch(InterruptedException e){}
(b)优先级
setPriority(int priority) 方法
(c)后台线程
1.普通线程:若还有普通线程,整个程序就不会结束
2.Daemon线程(后台线程):普通线程结束了,则后台线程自动终止
例:
import java.util.*;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t = new MyThread();
t.setDaemon(true);
t.start();
System.out.println( "Main--" + new Date());
try{ Thread.sleep(500); }
catch(InterruptedException ex){}
System.out.println("Main End");
}
}
class MyThread extends Thread
{
public void run()
{
for(int i=0;i<10;i++)
{
System.out.println( i + "--" + new Date());
try{ Thread.sleep(100);}
catch(InterruptedException ex){}
}
}
}
0–Thu Dec 14 16:59:04 CST 2017
Main–Thu Dec 14 16:59:04 CST 2017
1–Thu Dec 14 16:59:04 CST 2017
2–Thu Dec 14 16:59:04 CST 2017
3–Thu Dec 14 16:59:05 CST 2017
4–Thu Dec 14 16:59:05 CST 2017
Main End
4.线程的同步
(1)同时运行的线程需要共享数据
import java.util.*;
public class Test {
public static void main(String[] args)
{
Num num = new Num();
Thread counter1 = new Counter(num);
Thread counter2 = new Counter(num);
for(int i=0;i<10;i++)
{
if(!num.testEquals()) break;
try{
Thread.sleep(100);
}catch(InterruptedException e){}
}
}
}
class Num
{
private int x=0;
private int y=0;
void increase()
{
x++;
y++;
}
boolean testEquals()
{
boolean ok = (x==y);
System.out.println(x + "," + y + "Equal?" + ok);
return ok;
}
}
class Counter extends Thread
{
private Num num;
Counter(Num num)
{
this.num = num;
this.setDaemon(true);
this.setPriority(MIN_PRIORITY);
this.start();
}
public void run()
{
while(true)
{
num.increase();
}
}
}
(2)Synchronized
5.生产者-消费者问题
public class ProducerConsumer {
public static void main(String[] args)
{
CubbyHole c = new CubbyHole();
Producer p1 = new Producer(c);
Consumer c1 = new Consumer(c);
p1.start();
c1.start();
}
}
class Producer extends Thread{
private CubbyHole cubbyhole;
public Producer(CubbyHole c)
{
cubbyhole = c;
}
public void run()
{
for(int i=0;i<10;i++){
cubbyhole.put(i);
}
}
}
class Consumer extends Thread{
private CubbyHole cubbyhole;
public Consumer(CubbyHole c)
{
cubbyhole = c;
}
public void run()
{
int value = 0;
for(int i=0;i<10;i++){
value = cubbyhole.get();
}
}
}
class CubbyHole
{
private int data[] = new int[3];
private int index = 0;
public synchronized void put(int i)
{
while(index >= data.length)
{
try{
wait();
} catch(InterruptedException e){}
}
System.out.println("Producer " + " put: " + i);
data[index] = i;
index++;
notify();
}
public synchronized int get()
{
while(index<=0)
{
try{
wait();
} catch (InterruptedException e){}
}
index--;
int value = data[index];
System.out.println("Consumer " + " got: " + value);
notify();
return value;
}
}