什么是进程与线程与多线程
进程:进程是指一个内存中运行的应用程序
线程:线程是进程内一个相对独立的,可调度的执行单元,又称为轻量级进程。
多线程是指一个程序中包含多个执行流。
线程的生命历程
new(新生),runnable(就绪),running(运行),blocked(阻塞),dead(死亡)。
创建线程的方式
第一种是继承Thread类,请看如下代码:
package hhuc;
public class Test extends Thread {
Test(String name){
super(name);
}
@Override
public void run(){
for(int i = 0 ;i<5;i++){
System.out.println(Thread.currentThread().getName()+":"+i);
}
}
public static void main(String args[]) throws Exception{
Test thread1 = new Test("thread1");
Test thread2 = new Test("thread2");
thread1.start();
thread2.start();
for(int i = 0;i<5;i++)
System.out.println("主线程:"+i);
}
}
第二种方式是实现Runnable接口,请看如下代码:
package hhuc;
public class Test implements Runnable {
String name;
Test(String name){
this.name = name;
}
@Override
public void run(){
for(int i = 0 ;i<5;i++){
System.out.println(name+":"+i);
}
}
public static void main(String args[]) throws Exception{
Test test1 = new Test("thread1");
Test test2 = new Test("thread2");
Thread thread1 = new Thread(test1);
Thread thread2 = new Thread(test2);
thread1.start();
thread2.start();
for(int i = 0;i<5;i++)
System.out.println("主线程:"+i);
}
}
通过以上代码,我们发现,主线程,thread1,thread2在交替远行,这是因为线程在进入start()(就绪状态)后,什么时候开始远行完全由CPU决定,CPU会给线程时间片,如果线程在一个时间片内不能运行结束,那么中断,进入就绪状态
线程的同步
线程同步:即当有一个线程在对内存进行操作时,其他线程都不可以对这个内存地址进行操作,直到该线程完成操作, 其他线程才能对该内存地址进行操作,而其他线程又处于等待状态。在Java中我们用锁的机制实现代码同步即关键字:synchronized,每一个对象都有一把唯一的锁,当线程进入synchronized代码块的时候,会自动获得当前对象的锁,会为synchronized代码块加锁,离开synchronized方法或代码块后,释放锁,其他线程才有机会获得这把锁,请看如下代码:
未同步
package hhuc;
public class Store {
int number = 10;
public void shopping(){
number--;
System.out.println(Thread.currentThread().getName()+":"+number);
}
public static void main(String args[]){
Store store = new Store();
ConsumerThread consumerThread1 = new ConsumerThread(store);
ConsumerThread consumerThread2 = new ConsumerThread(store);
consumerThread1.start();
consumerThread2.start();
}
}
class ConsumerThread extends Thread{
Store store;
ConsumerThread(Store store){
this.store = store;
}
@Override
public void run(){
for(int i = 0;i<5;i++){
store.shopping();
try {
sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
同步代码
package hhuc;
public class Store {
int number = 10;
synchronized public void shopping(){
number--;
System.out.println(Thread.currentThread().getName()+":"+number);
}
public static void main(String args[]){
Store store = new Store();
ConsumerThread consumerThread1 = new ConsumerThread(store);
ConsumerThread consumerThread2 = new ConsumerThread(store);
consumerThread1.start();
consumerThread2.start();
}
}
class ConsumerThread extends Thread{
Store store;
ConsumerThread(Store store){
this.store = store;
}
@Override
public void run(){
for(int i = 0;i<5;i++){
store.shopping();
try {
sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}