理解进程和线程的概念:进程表示一个任务执行的全部过程 如播放器播放音乐,线程是在共享线程资源的条件下处理多个任务 比如上面的播放音乐的时候 会出字幕,出声音 这些细节的线程
实现线程 Thread 下的run() 方法.
class ProcessThread extends Thread{
int i;
public run(){
while(true){
System.out.println(i);
i--;
}
}
}
调用 Thread th = new ProcessThread()
th.start();
Thread th1 = new ProcessThread();
th1.start()
线程里的i 变量是分别打印的 不是共享 如果采用方法2.
class ProcessRunnable extends Runnable
{
while(true){
System.out.println(i);
i--;
}
}
引用
Runnable runnable = new ProessRunnable();
Thread th = new Thread(runnable);
Thread th1 = new Thread(runnable);
th.start();
th1.start();
其中的变量i 是共享的
线程安全性的问题
1.线程协作(join)
class ThreadAnth extends Thread
{
while(true){
for( int i=0;i<1000;i++)
{
sum+=i;
}
}
}
main(){
private ThreadAnth th= new ThreadAnt();
th.start();
//System.out.println( "结果是:"+sum); 线程并不打印出真正的结果 说明线程还没有执行完毕
System.out.println("线程等待的时候也能被执行");
try{
th.join();
}catch(Excception ex){}
System.out.println( "结果是:"+sum); 线程能打印出真正的结果 说明线程一直在等待join 完毕
2.线程同步 synchronized
当2个线程在同时使用一个变量的时候出现资源暂用的同时也被另外一个线程抢占 导致整个方法里的程序执行错误 这个时候需要用到 synchroniazed setTicket() 修饰符在加锁 保证整个方法里的东西执行完后 另外一个线程才能去抢占资源