
package threadProj;
public class Letter implements Runnable {
private char[] letter = new char[26];
public Letter() {
int j =0;
for(char i = 'a'; i<='z' ; i++) {
letter[j++] = i;
}
}
@Override
public void run() {
for(char n: letter) {
System.out.println(n);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package threadProj;
public class ThreadTest {
public static void main(String[] args) {
Letter letterRunnable = new Letter();
Thread r1 = new Thread(letterRunnable);
r1.start();
}
}
-
Thread.currentThread()
优先级: thread.currentThread().getPriority();
mt1. setPriority(Thread.MAX_PRIORITY); -
线程同步
package indi.yuan.wheather;
public class Wheather {
private int temperature;
private int humidity;
public boolean canRead = false;
public void setTemperature(int temperature) {
this.temperature = temperature;
}
public void setHumidity(int humidity) {
this.humidity = humidity;
}
public synchronized void generate() {
if(canRead) {
try {
// 暂停线程
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int temp = (int) (Math.random() * 40);
int humi = (int) (Math.random() * 100);
this.setHumidity(humi);
this.setTemperature(temp);
canRead = true;
// 唤起线程
notifyAll();
}
public synchronized void read() {
if(!canRead) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(" 温度" + this.temperature + "湿度 " + this.humidity);
canRead = false;
}
public String toString() {
return "读取天气方法";
}
}
package indi.yuan.wheather;
public class GenerateWeather implements Runnable {
Wheather wheather;
GenerateWeather(Wheather wheather){
this.wheather = wheather;
}
@Override
public void run() {
while(true) {
wheather.generate();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package indi.yuan.wheather;
public class ReadWeather implements Runnable {
Wheather wheather;
ReadWeather(Wheather wheather){
this.wheather = wheather;
}
@Override
public void run() {
while(true) {
wheather.read();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
package indi.yuan.wheather;
public class WheatherTest {
public static void main(String[] args) {
Wheather wheather = new Wheather();
new Thread(new GenerateWeather(wheather)).start();
new Thread(new ReadWeather(wheather)).start();
}
}
网友评论