Java并发编程-线程

1.线程的状态

线程有一下一些状态,init,ready-to-run,Running,Sleeping,Waiting,Blocked和Dead,并在一些事件的触发下在这些状态之间进行转移,状态转移如下图:


2.线程的创建

    (1)继承Thread类

        public class Demo1 extends Thread {
    public void run() {
System.out.println("getName() + 线程执行了...")
    }
    public static void main(String[] args) {
Demo1 d1 = new Demo1();
Demo2 d2 = new Demo2();

d1.start();
d2.start();
    }
}

    (2)实现Runnable接口

        public class Demo2 implement Runnable {
    public void run() {
while (true) {
System.out.println("thread running...")
}
    }

    public static void main(String[] args) {
Thread thread = new Thread(new Demo2());
thread.start();
    }
    }

    (3)匿名内部类的方法

public class Demo3 {

public static void main(String[] args) {
new Thread() {
public void run() {
System.out.println("thread start...");
};
}.start();

new Thread(new Runnable() {
public void run() {
                                System.out.println("thread start...");
}
}.start();
}
}

    (4)带返回值的线程

 public class Demo4 implements Callable<Integer>{
public static void main(String[] args) {
Demo4 d = new Demo4();
FutureTask<Integer> task = new FutureTask<>(d);

Thread t = new Thread(task);
t.start();

Integer result = task.get();
System.out.println(result);
}

public Integer call() throws Exception {
System.out.println("正在计算");
Thread.sleep(3000);
return 1;
}
}

    (5)定时器(quartz)

public class Demo5 {
public static void main(String[] args) {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
System.out.println("timertask is run")
}
}, 0, 1000);
}
}

    (6)线程池的实现

 public class Demo6 {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newFixedThreadPool(10);
threadPool.execute(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName())
}
});

threadPool.shutdown();
}
}

    (7)Lambda表达式实现

public class Demo7 {
public static void main(String[] args) {
List<Integer> values = Arrays.asLIst(10, 20, 30, 40);
int result = new Demo7().add(values);
System.out.println(result);

}

public int add(List<Integer> values) {
values.parallelStream().forEach(System.out.println);
return values.parallelStream().mapToInt(a -> a).sum();
}
}

   (8)Spring实现多线程

@Configuration
@ComponentScan("com.roocn.test")
@EnableAsync
public class Config {

}

@Service
public class DemoService() {
@Async
public void a() {
System.out.println("a");
}

@Async
public void b() {
System.out.println("b");
}
}
public class Main {
public static void mian(String[] args) {

AnnotationConfigApplicationContext ac = 

                new AnnotationConfigApplicationContext(Config.class);

ac.getBean(DemoService.class);

ds.a();
ds.b();
}
}        
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值