java 多线程

1、  线程是程序内部的执行过程。

2、  线程和进程的区别

1.  每个进程都有独立的代码和数据空间(进程上下文),进程间的切换会有较大的开销

2.  线程可以看成是轻量级的进程,同一类线程共享代码和数据空间,每个线程有独立的运行栈和程序计数器 (PC), 线程的切换开销小。

3.  在操作系统中同时运行多个任务程序叫做多进程。

4.  在同一应用程序中有多个程序控制流同时执行叫做多线程。

 

下面的程序开始到结束只有一条执行线索

package com.thread;

// 这个程序只有一条执行线索,用 Debug 模式观察更为清晰

public class TestSingle {

    Thread a = new Thread();

    public static void main(String [] args) {

       fn1 ();

    }

    private static void fn1() {

       System. out .println( "fn1" );

       fn2 ();

       fn3 ();

    }

    private static void fn2() {

       System. out .println( "fn2" );

    }

    private static void fn3() {

       System. out .println( "fn3" );

    }

}

 
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

线程同步

package com.thread.sync;

// 如果不加 synchronized ,当 m1 被锁定的时候, m2 也能执行,是道面试

public class TT implements Runnable {

    int a = 100;

    public synchronized void m1() throws InterruptedException {

       System. out .println( "m1start..." );

       a = 1000;

       Thread.sleep (5000);

       System. out .println( "m1:" + a );

       System. out .println( "m1end..." );

    }

    // 如果这里加上 synchronized ,当 m2 执行的时候,

    // 拿到了当前对象的锁, m1 不能执行,理解互斥锁。

    public   /*synchronized*/ void m2() throws InterruptedException {

       System. out .println( "m2start......" );

       Thread.sleep (2500);

       a = 2000;

       System. out .println( "m2end..." );

    }

    @Override

    public void run() {

       try {

           m1();

       } catch (InterruptedException e) {

           e.printStackTrace();

       }  

    }

    public static void main(String[] args) throws Exception {

       System. out .println( "mainstart..." );

       TT tt = new TT();

       Thread t = new Thread(tt);

       t.start();

       tt.m2();

       System. out .println( "main:" + tt. a );

    }

}

 
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

wait

       使正在当前对象访问的线程 wait, wait 时,对象的锁不在归对象的线程所有!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值