Java 多线程
Posted esrevinud
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java 多线程相关的知识,希望对你有一定的参考价值。
Java线程编程
Thread类和Runnable接口
Runnable
是Java中所有线程相关的类必须实现的接口
创建线程
有两种方式,继承Thread
类和实现Runnable
接口
继承Thread类
public class Main extends Thread{
@Override
public void run() {
//调用getName()返回线程名称
System.out.println(getName() + " is running");
}
public static void main(String[] args) {
//实例化Main对象
Main one = new Main();
Main two = new Main();
Main three = new Main();
//启动线程
one.start();
two.start();
three.start();
}
}
实现Runnable接口
public class Main implements Runnable{
@Override
public void run () {
//Thread的类方法Thread.currentThread()返回当前线程对象,再调用getName()返回线程名称
System.out.println(Thread.currentThread().getName() + " is running");
}
public static void main(String[] args) {
//实例化Main类
Main one = new Main();
Main two = new Main();
Main three = new Main();
//将Main的实例代入Thread构造函数,构造出Thread对象
Thread the_one = new Thread(one);
Thread the_two = new Thread(two);
Thread the_three = new Thread(three);
//启动线程
the_one.start();
the_two.start();
the_three.start();
}
}
线程间的资源共享
//个线程间共享用于控制循环的变量i
public class Main implements Runnable{
// 这里的变量就是属于共享资源
int i=0;
// run方法内部是每个线程内部的资源和代码
@Override
public void run() {
// Thread的类方法Thread.currentThread()返回当前线程对象,再调用getName()返回线程名称
// System.out.println(Thread.currentThread().getName()+" is running");
for (; i < 10; i ++) {
System.out.println(Thread.currentThread().getName() + " is running for the "+i);
}
// System.out.println(message);
}
public static void main (String[] args) {
//实例化Main类
Main one = new Main();
// Main two=new Main();
// Main three=new Main();
//将Main的实例代入Thread构造函数,构造出Thread对象
Thread the_one = new Thread(one);
Thread the_two = new Thread(one);
Thread the_three = new Thread(one);
//启动线程
System.out.println(the_one.getId());
System.out.println(the_two.getId());
System.out.println(the_three.getId());
the_one.start();
the_two.start();
the_three.start();
}
}
设置线程优先级
//setPriority()设置,参数可以是常量也可以是[1,10]整数
the_one.setPriority(Thread.MAX_PRIORITY);
System.out.println(the_one.getPriority()); //输出打印10
优先级常量有三个等级
- Thread.MAX_PRIORITY
- Thread.MIN_PRIORITY
- Thread.NORM_PRIORITY
线程同步锁
使用synchronized
修饰符,可修饰方法和语句块
修饰方法
//object method
public synchronized void printEach() {
//once for loop
}
//static method
public static synchronized void printEach() {
//once for loop
}
//statement block
//this表示为当前对象,也可以使用别的对象作为参数
synchronized(this) {
//code
}
以上是关于Java 多线程的主要内容,如果未能解决你的问题,请参考以下文章