public class Test{
public static void main(String[] args) throws Exception{
TestThread testThread = new TestThread();
testThread.run();
}
}
运行结果:
Java线程篇
2.实现Runnable接口
经典的生产者和消费者
class Product implements Runnable{//生产者
private Message message;
Product(Message message) {
this.message = message;
}
public void run() {
for (int x = 0 ; x < 100 ; x++){
if (x % 2 == 0){
this.message.set("生产者","生产");
}else {
this.message.set("消费者","消费");
}
}
}
}
----
class Consumer implements Runnable{//消费者
private Message message;
public Consumer(Message message) {
this.message = message;
}
public void run() {
for (int x = 0 ; x < 100 ; x++){
System.out.println(this.message.get());
}
}
}
----
class Message{ //消息中心
private String title;
private String content;
private boolean flag = true;//表示生产或者消费的形式
// flag = true 允许生产,不允许消费 flag= false 允许消费,不允许生产
synchronized void set(String title, String content){
if (!flag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.title = title;
this.content = content;
this.flag = false; //生产完成
notify();//唤醒等待的线程
}
synchronized String get(){
if (flag == true){
try {
super.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
return this.title + " ------------ "+this.content;
}finally {
this.flag = true; // 可继续生产
notify();//唤醒等待线程
}
}
}
----
public class Producer {
public static void main(String[] args) throws Exception{
Message message = new Message();
new Thread(new Product(message),"生产者").start();//启动生产者线程
new Thread(new Consumer(message),"消费者").start();//启动消费者线程
}
}
运行结果
Java线程篇
3.实现Callable接口
class TheThread implements Callable<String>{
private boolean flag = false;
@Override
public String call() throws Exception {
synchronized (this){
if (this.flag==false){
this.flag = true;
return Thread.currentThread().getName()+"抢答成功";
}else {
return Thread.currentThread().getName()+"抢答失败";
}
}
}
}
public class Competition {
public static void main(String[] args) throws ExecutionException, InterruptedException {
TheThread theThread = new TheThread();
FutureTask<String> futureTaskA = new FutureTask<>(theThread);
FutureTask<String> futureTaskB = new FutureTask<>(theThread);
FutureTask<String> futureTaskC = new FutureTask<>(theThread);
new Thread(futureTaskA,"竞赛者A").start();
new Thread(futureTaskB,"竞赛者B").start();
new Thread(futureTaskC,"竞赛者C").start();
System.out.println(futureTaskA.get());
System.out.println(futureTaskB.get());
System.out.println(futureTaskC.get());
}
}
Java线程篇
4.使用线程池
class ExecutorTest{
public static void main(String[] args) {
// 创建线程池
ThreadPoolExecutor service = new ThreadPoolExecutor(5, 200,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(1024),
new ThreadFactoryBuilder().setNameFormat("test-thread-pool-%d").build(),
new ThreadPoolExecutor.AbortPolicy());
Runnable runnable = () -> {
try {
TimeUnit.SECONDS.sleep(1);
System.out.println("线程1执行");
} catch (InterruptedException e) {
e.printStackTrace();
}
};
Runnable runnable1 = () -> {
try {
TimeUnit.SECONDS.sleep(2);
System.out.println("线程2执行");
} catch (InterruptedException e) {
e.printStackTrace();
}
};
int num = 10;
for (int i = 0; i < num; i++) {
service.execute(runnable);
service.execute(runnable1);
}
}
}
public class Volatile{
public static void main(String[] args) throws Exception{
MyThread myThread = new MyThread();
new Thread(myThread,"票贩子A").start();
new Thread(myThread,"票贩子B").start();
new Thread(myThread,"票贩子C").start();
}
}
public class Daemon {
public static void main(String[] args) throws Exception{
Thread userThread = new Thread(() -> {
for (int x = 0 ; x < 10 ; x++) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在执行 x = " + x);
}
},"执行线程");
Thread daemonThread = new Thread(() -> {
for (int x = 0 ; x < Integer.MAX_VALUE ; x++){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在执行 x = " + x);
}
},"守护线程");
daemonThread.setDaemon(true);//将daemonThread设为守护线程
userThread.start();
daemonThread.start();
}
}
Java线程篇
在Thread类提供了以下的守护线程的操作方法,可自行查看源码
设置为守护线程:
public final void setDaemon(boolean on) {
checkAccess();
if (isAlive()) {
throw new IllegalThreadStateException();
}
daemon = on;
}
判断是否为守护线程
public final boolean isDaemon() {
return daemon;
}
停止线程
public class StopThread {
public static boolean flag = true;
public static void main(String[] args) throws Exception{
new Thread(() -> {
long num = 0;
while (flag){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "正在执行 num = " + num++);
}
},"执行线程").start();
Thread.sleep(200);//线程运行200毫秒
flag = false;//停止线程
}
}