包(package):对类文件进行分类管理。给类提供多层命名空间。写在程序文件的第一行。类名的全称是包名.类名 包也是一种封装形式。
总结:包与包之间进行访问,被访问的包中的类以及类中的成员,需要public修饰。
不同包中的子类还可以直接访问父类中被protected权限修饰的成员。
包与包之间可以使用的权限只有两种:public和protected。
为了简化类名书写,使用一个关键字,import。
import导入的是包中的类。
建议,不要写通配符*,需要用到包中的哪个类,就导入哪个类。
建立包名不要重复,可以用url来完成定义,url是唯一的。
Jar包:java的压缩包。
方便项目的携带。方便于使用,只要在classpath设置jar路径即可。数据库驱动,SSH框架等都是以jar包体现。
进程:是一个正在执行中的程序。
每一个进程执行都有一个执行顺序。该顺序是一个执行路径,或者叫一个控制单元。
线程:就是进程中的一个独立的控制单元。线程在控制着进程的执行。
一个进程中至少有一个线程。
Jvm启动的时候会有一个进程java.exe ,该进程中至少一个线程负责java程序的执行。而且这个线程运行的代码存在于main方法中。该线程称之为主线程。
扩展:其实更细节说明jvm,jvm启动不止一个线程,还有负责垃圾回收机制的线程。
如何在自定义的代码中,自定义一个线程呢?
通过对api的查找,java已经提供了对线程这类事物的描述。就是Thread类。
创建线程的第一种方式:继承Thread类。
步骤:
1、定义类继承Thread。
2、复写Thread类中的run方法。
目的:将自定义代码存储在run方法,让线程运行。
3、调用线程的start方法。
该方法两个作用:启动线程,调用run方法。
发现运行结果每一次都不相同。
因为多个线程都获取cpu的执行权。cpu执行到谁,谁就运行。
明确一点,在某一个时刻,只能有一个程序在运行。(多核除外)
cpu在做着快速的切换,以达到看上去是同时运行的效果。
我们可以形象的把多线程的运行行为是在互相抢夺cpu执行权。
这就是多线程的一个特性:随机性。谁抢到谁执行,至于执行多长,cpu说得算。
为什么要覆盖run方法呢?
Thread类用于描述线程,该类定义了一个功能,用于存储线程要运行的代码。该存储功能就是run方法。
也就是说Thread类中的run方法,用于存储线程要运行的代码。
class Demo extends Thread
{
publicvoid run()
{
for(intx=0;x<60;x++)
System.out.println("demorun"+x);
}
}
class ThreadDemo
{
publicstatic void main(String[] args)
{
Demod=new Demo();
d.start();
for(intx=0;x<60;x++)
System.out.println("HelloWorld!"+x);
}
}
原来线程都有自己默认的名称。Thread-编号 该编号从0开始。
currentThread():获取当前线程对象。
getName():获取线程名称。
设置线程名称:setName或者构造函数。
创建线程的第二种方式:实现Runnable接口
步骤:
1、 定义类实现Runnable接口。
2、 覆盖Runnable接口中的run方法。
将线程要运行的代码存放在该run方法中。
3、 通过Thread类建立线程对象。
4、 将Runnable接口的子类对象作为实际参数传递给Thread类的构造函数。
为什么要将Runnable接口的子类对象传递给Thread的构造函数。
因为自定义的run方法所属的对象是Runnable接口的子类对象。
所以要让线程去指定指定对象的run方法。就必须明确该run方法所属对象。
5、 调用Thread类的start方法开启线程并调用Runnable接口子类的run方法。
实现方式和继承方式的区别?(面试题)
实现方式的好处:避免了单继承的局限性。
在定义线程时,建议使用实现方式。
两种方式区别:
继承Thread:线程代码存放在Thread子类run方法中。
实现Runnable:线程代码存放在接口子类的run方法中。
示例代码:
/*
需求:简单的卖票程序。
多个窗口同时卖票。
*/
classTicket implements Runnable
{
private int tick=100;
public void run()
{
while(true)
{
if(tick>0)
{
System.out.println(Thread.currentThread().getName()+"sale:"+tick--);
}
}
}
}
class TicketDemo
{
public static void main(String[] args)
{
/*Ticket t1=new Ticket();
Ticket t2=new Ticket();
Ticket t3=new Ticket();
Ticket t4=new Ticket();*/
Ticket t=new Ticket();
Thread t1=new Thread(t);
Thread t2=new Thread(t);
Thread t3=new Thread(t);
Thread t4=new Thread(t);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
多线程会出现安全问题。问题原因:
当多条语句在操作同一个线程共享数据时,一个线程对多条语句只执行了一部分,还没有执行完,另一个线程参与进来执行。导致共享数据的错误。
解决办法:
对多条操作共享数据的语句,只能让一个线程都执行完,在执行过程中,其他线程不可以参与执行。
java对于多线程的安全问题提供了专业的解决方式。就是同步代码块。
synchronized(对象)
{
需要被同步的代码
}
对象如同锁,持有锁的线程可以在同步中执行。
没有持有锁的线程即使获取cpu的执行权,也进不去,因为没有获取锁。
同步的前提:
1、 必须要有两个或者两个以上的线程。
2、 必须是多个线程使用同一个锁。
必须保证同步中只能有一个线程在运行。
好处:解决了多线程的安全问题。
弊端:多个线程需要判断锁,较为消耗资源。
同步函数用的是哪一个锁?
函数需要被对象调用。那么函数都有一个所属对象引用,就是this。
所以同步函数使用的锁是this。
如果同步函数被静态修饰后,使用的锁是什么呢?
不是this,因为静态方法中不可以定义this。
静态进内存时,内存中没有本类对象,但是一定有该类对应的字节码文件对象。类名.class 该对象的类型是class。
静态的同步方法,使用的锁是该方法所在类的字节码文件对象。类名.class
懒汉式的特点在于实例的延迟加载
问题:当多线程访问时会出现安全问题,可以加同步解决,加同步的方式用同步代码块和同步函数都行。但稍微有些低效,用双重判断的形式能解决这个问题。加同步的时候使用的锁是哪一个?该类所属的字节码文件对象。
class Single
{
privatestatic Single s=null;
privateSingle(){}
publicstatic Single getInstance()
{
if(s==null)
{
synchronized(Single.class)
{
if(s==null)
s=new Single();
}
}
returns;
}
}
死锁的例子,同步嵌套同步:
class Testimplements Runnable
{
private boolean flag;
Test(boolean flag)
{
this.flag=flag;
}
public void run()
{
if(flag)
{
synchronized(MyLock.locka)
{
System.out.println("iflocka");
synchronized(MyLock.lockb)
{
System.out.println("iflockb");
}
}
}
else
{
synchronized(MyLock.lockb)
{
System.out.println("elselockb");
synchronized(MyLock.locka)
{
System.out.println("elselocka");
}
}
}
}
}
classMyLock
{
static Object locka=new Object();
static Object lockb=new Object();
}
class DeadLockTest
{
public static void main(String[] args)
{
Thread t1=new Thread(newTest(true));
Thread t2=new Thread(newTest(false));
t1.start();
t2.start();
}
}
线程间通信:
其实就是多个线程在操作同一个资源,但是操作的动作不同。
classResource
{
String name;
String sex;
boolean flag=false;
}
class Inputimplements Runnable
{
private Resource r;
Input(Resource r)
{
this.r=r;
}
public void run()
{
int x=0;
while(true)
{
synchronized(r)
{
if(r.flag)
try{r.wait();}catch(Exceptione){}//等待
if(x==0)
{
r.name="mike";
r.sex="man";
}
else
{
r.name="莉莉";
r.sex="女";
}
x=(x+1)%2;
r.flag=true;
r.notify();//唤醒
}
}
}
}
classOutput implements Runnable
{
private Resource r;
Output(Resource r)
{
this.r=r;
}
public void run()
{
while(true)
{
synchronized(r)
{
if(!r.flag)
{
try{r.wait();}catch(Exceptione){}
}
System.out.println(r.name+"...."+r.sex);
r.flag=false;
r.notify();
}
}
}
}
classInputOutputDemo
{
public static void main(String[] args)
{
Resource r=new Resource();
Input in=new Input(r);
Output out=new Output(r);
Thread t1=new Thread(in);
Thread t2=new Thread(out);
t1.start();
t2.start();
}
}
wait();
notify();
notifyAll();
都使用在同步中,因为要对持有监视器(锁)的线程操作。
所以要使用在同步中,因为只有同步才有锁。
为什么这些操作线程的方法要定义Object类中呢?
因为这些方法在操作同步中线程时,都必须要标识它们所操作线程持有的锁。
只有同一个锁上的被等待线程,可以被同一个锁上notify唤醒。
不可以对不同锁中的线程进行唤醒。
也就是说,等待和唤醒必须是同一个锁。
而锁可以是任意对象,所以可以被任意对象调用的方法定义在Object类中。
优化后代码:
classResource
{
private String name;
private String sex;
private boolean flag=false;
public synchronized void set(Stringname,String sex)
{
if(flag)
try{this.wait();}catch(Exceptione){}
this.name=name;
this.sex=sex;
flag=true;
this.notify();
}
public synchronized void out()
{
if(!flag)
try{this.wait();}catch(Exceptione){}
System.out.println(name+"...."+sex);
flag=false;
this.notify();
}
}
class Inputimplements Runnable
{
private Resource r;
Input(Resource r)
{
this.r=r;
}
public void run()
{
int x=0;
while(true)
{
if(x==0)
{
r.set("mike","man");
}
else
{
r.set("莉莉","女");
}
x=(x+1)%2;
//r.flag=true;
//r.notify();//唤醒
}
}
}
class Outputimplements Runnable
{
private Resource r;
Output(Resource r)
{
this.r=r;
}
public void run()
{
while(true)
{
r.out();
}
}
}
classInputOutputDemo
{
public static void main(String[] args)
{
Resource r=new Resource();
new Thread(newInput(r)).start();
new Thread(newOutput(r)).start();
/*Input in=new Input(r);
Output out=new Output(r);
Thread t1=new Thread(in);
Thread t2=new Thread(out);
t1.start();
t2.start();*/
}
}
对于多个生产者和消费者为什么要定义while判断标记。
原因:让被唤醒的线程再一次判断标记。
为什么定义notifyAll?
因为需要唤醒对方线程。
因为只用notify,容易出现只唤醒本方线程的情况。
classProducerConsumerDemo
{
public static void main(String[] args)
{
Resource r=new Resource();
Producer pro=new Producer(r);
Consumer con=new Consumer(r);
Thread t1=new Thread(pro);
Threadt2=new Thread(pro);
Thread t3=new Thread(con);
Thread t4=new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
classResource
{
private String name;
private int count=1;
private boolean flag=false;
public synchronized void set(Stringname)
{
while(flag)
try{this.wait();}catch(Exceptione){}
this.name=name+"--"+count++;
System.out.println(Thread.currentThread().getName()+"..生产者.."+this.name);
flag=true;
this.notifyAll();
}
public synchronized void out()
{
while(!flag)
try{this.wait();}catch(Exception e){}
System.out.println(Thread.currentThread().getName()+"..消费者....."+this.name);
flag=false;
this.notifyAll();
}
}
classProducer implements Runnable
{
private Resource res;
Producer(Resource res)
{
this.res=res;
}
public void run()
{
while(true)
{
res.set("商品");
}
}
}
classConsumer implements Runnable
{
private Resource res;
Consumer(Resource res)
{
this.res=res;
}
public void run()
{
while(true)
{
res.out();
}
}
}
生产者消费者 lock升级版:
JDK1.5 中提供了多线程升级解决方案。
将同步synchronized替换成显示lock操作。
将Object中的wait,notify, notifyAll,替换成了Condition对象。
该对象可以通过Lock锁进行获取。
该实例中,实现了本方只唤醒对方操作。
importjava.util.concurrent.locks.*;
classProducerConsumerDemo2
{
public static void main(String[] args)
{
Resource r=new Resource();
Producer pro=new Producer(r);
Consumer con=new Consumer(r);
Thread t1=new Thread(pro);
Threadt2=new Thread(pro);
Thread t3=new Thread(con);
Thread t4=new Thread(con);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
classResource
{
private String name;
private int count=1;
private boolean flag=false;
private Lock lock=new ReentrantLock();
private Conditioncondition_pro=lock.newCondition();
private Conditioncondition_con=lock.newCondition();
public void set(String name) throwsInterruptedException
{
lock.lock();
try
{
while(flag)
condition_pro.await();
this.name=name+"--"+count++;
System.out.println(Thread.currentThread().getName()+"..生产者.."+this.name);
flag=true;
condition_con.signal();
}
finally
{
lock.unlock();
}
}
public void out()throwsInterruptedException
{
lock.lock();
try
{
while(!flag)
condition_con.await();
System.out.println(Thread.currentThread().getName()+"..消费者....."+this.name);
flag=false;
condition_pro.signal();
}
finally
{
lock.unlock();
}
}
}
classProducer implements Runnable
{
private Resource res;
Producer(Resource res)
{
this.res=res;
}
public void run()
{
while(true)
{
try
{
res.set("商品");
}
catch(InterruptedException e)
{
}
}
}
}
classConsumer implements Runnable
{
private Resource res;
Consumer(Resource res)
{
this.res=res;
}
public void run()
{
while(true)
{
try
{
res.out();
}
catch(InterruptedException e)
{
}
}
}
}
stop方法已经过时。
如何停止线程?
只有一种,run方法结束。
开启多线程运行,运行代码通常是循环结构。
只要控制住循环,就可以让run方法结束,也就是线程结束。
特殊情况:
当线程处于了冻结状态。
就不会读取到标记,那么线程就不会结束。
当没有指定的方式让冻结的线程恢复到运行状态时,这时需要对冻结进行清除,
强制让线程恢复到运行状态中来。这样就可以操作标记让线程结束。
Thread类提供该方法interrupt();
classStopThread implements Runnable
{
private boolean flag=true;
public synchronized void run()
{
while(flag)
{
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println(Thread.currentThread().getName()+"....Exception");
flag=false;
}
System.out.println(Thread.currentThread().getName()+"....run");
}
}
public void changeFlag()
{
flag=false;
}
}
classStopThreadDemo
{
public static void main(String[] args)
{
StopThread st=newStopThread();
Thread t1=new Thread(st);
Thread t2=new Thread(st);
t1.start();
t2.start();
int num=0;
while(true)
{
if(num++==60)
{
//st.changeFlag();
t1.interrupt();
t2.interrupt();
break;
}
System.out.println(Thread.currentThread().getName()+"......"+num);
}
}
}
join:
当A线程执行到了B线程的.join方法,A就会等待。等B线程都执行完,A才会执行。
join可以用来临时加入线程执行。