Cirry's Blog

Java多线程编程

2019-09-29
技术
java
最后更新:2024-03-22
2分钟
364字

范例: 定义一个线程

1
package cn.cccc.demo;
2
class MeThread extends Thread{
3
private String title;
4
public MeThread(String title){
5
this.title = title;
6
}
7
public void run(){
8
for(int x = 0; x < 10; x++){
9
System.out.println(this.title + "运行 x = "+ x);
10
}
11
}
12
}
13
public class MyThread {
14
public static void main(String[] args) {
15
// TODO Auto-generated method stub
6 collapsed lines
16
new MeThread("线程A").start();
17
new MeThread("线程B").start();
18
new MeThread("线程C").start();
19
20
}
21
}

利用卖票资源实现多个线程资源的并发访问

1
package cn.cccc.demo;
2
class MyThread implements Runnable{
3
private int ticket = 5;
4
5
@Override
6
public void run (){ // 线程的主体类
7
for(int x = 0; x < 100; x++) {
8
if(this.ticket > 0 ) {
9
System.out.println("卖票、ticket = " + this.ticket--);
10
}
11
}
12
}
13
}
14
public class ThreadDemo {
15
public static void main(String[] args) {
7 collapsed lines
16
// TODO Auto-generated method stub
17
MyThread mt = new MyThread();
18
new Thread(mt).start();
19
new Thread(mt).start();
20
new Thread(mt).start();
21
}
22
}

三个线程访问一个资源,总共卖五张票

callable实现多线程 从最传统的开发来讲入股偶要进行多线程的实现肯定依靠的就是Runnable,但是Runnable接口有一个缺陷就是执行后无法获取一个返回值。 Runnable的run()方法是没有返回值的。所以从jdk1.5之后就提出了一个新的线程实现 接口:java.util.concurrent.Callable接口。

1
package cn.cccc.demo;
2
import java.util.concurrent.Callable;
3
import java.util.concurrent.ExecutionException;
4
import java.util.concurrent.FutureTask;
5
class MyThread implements Callable{
6
public String call() throws Exception{
7
for(int x = 0 ; x < 10; x++){
8
System.out.println("********线程执行x+" + x);
9
}
10
return "线程执行完毕";
11
}
12
}
13
public class ThreadDemo {
14
public static void main(String[] args) throws InterruptedException, ExecutionException {
15
// TODO Auto-generated method stub
8 collapsed lines
16
17
FutureTask<String> task = new FutureTask<>(new MyThread());
18
new Thread(task).start();
19
System.out.println("【线程返回数据】"+ task.get());
20
21
22
}
23
}
本文标题:Java多线程编程
文章作者:Cirry
发布时间:2019-09-29
版权声明:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
感谢大佬送来的咖啡☕
alipayQRCode
wechatQRCode