「java多线程经典题目」java关于线程的题目
今天给各位分享java多线程经典题目的知识,其中也会对java关于线程的题目进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!
本文目录一览:
Java多线程题目
看看是不是你想要的这种方法
public class TheadTest extends Thread{
private static ListString list=new ArrayListString();
public static void main(String[] args) {
Runnable b = new RunableTest(list);
new Thread(b).start();
Thread a = new TheadTest();
a.start();
}
@Override
public void run() {
add();
}
public void add(){
if(list!=null){
for(int i=1;i=10;i++){
System.out.println("add:"+i);
synchronized(list) {
list.add(String.valueOf(i));
}
}
}else{
try {
sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class RunableTest implements Runnable{
public ListString list;
public RunableTest(ListString list) {
this.list = list;
}
@Override
public void run() {
try {
minus();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void minus() throws InterruptedException {
if(list!=null){
boolean k =true;
while(k){
if(list.size()=0){
sleep(100);
}else{
for(int i=list.size();i0;i--){
System.out.println("minus:"+list.get(i-1));
synchronized(list) {
list.remove(i - 1);
}
}
k=false;
}
}
}
}
}
(大一java题目) 多线程
import java.util.*;
public class Exam
{
public static void main(String[] args) throws Exception
{
for(Config cg : Exam.getConfigs())
new MyThread(cg).start();
}
private static Config[] getConfigs()
{
return new Config[]
{
new Config("温度",20,40,500),
new Config("湿度",70,90,400),
new Config("光线强度",20,80,300)
};
}
}
class Config
{
Config(String s,int min,int max,int delay)
{
this.s=s;
this.min=min;
this.max=max;
this.delay=delay;
}
final String s;
final int min,max,delay;
}
class MyThread extends Thread
{
MyThread(Config cg)
{
this.cg=cg;
}
public void run()
{
int temp=cg.max-cg.min+1;
while(!Exit)
{
try
{
System.out.printf("当前%s:%d",cg.s,R.nextInt(temp)+cg.min);
System.out.println();
Thread.sleep(cg.delay);
}
catch(Exception ex)
{
}
}
}
private static final Random R=new Random(100);
private final Config cg;
static boolean Exit=false;
}
(java大一题目)多线程
public class Test {
public static final String mutex = "XXXXXXXXX";
private static int money = 1000;
public static void main(String[] args) {
Thread t1 = new Thread(new myThread("A"));
Thread t2 = new Thread(new myThread("B"));
t1.start();
t2.start();
}
public static class myThread implements Runnable {
private String people;
private int index = 0;
private int total = 0;
public myThread(String people) {
this.people = people;
}
@Override
public void run() {
while(true) {
synchronized (mutex) {
if(money = 0) {
int a=(int)(Math.random()*1000+100)/100*100;
if(money a ) {
System.out.println("余额不足");
break;
}
money -= a;
total += a;
index++;
System.out.println(people + "第" + index + "次取" + a + "元, 总共取了" + total);
}else {
break;
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
}
}
关于java多线程经典题目和java关于线程的题目的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。
发布于:2022-12-04,除非注明,否则均为
原创文章,转载请注明出处。